PHP+JS: How to do Fileuploads in HTML Form as Content-Type Multipart (via JS)?

You can use a FormData object to get the values of your form, and then append a blob version of your canvas into the FormData.

This blob will be seen as a file by the server.

Unfortunately, all browsers still don’t support the native canvas.toBlob() method, and even worth, all implementations are not the same.
All major browsers now support the toBlob method, and you can find a polyfill on mdn for older browsers.

// the function to create and send our FormData
var send = function(form, url, canvas, filename, type, quality, callback) {

  canvas.toBlob(function(blob){
    var formData = form ? new FormData(form) : new FormData();
    formData.append('file', blob, filename);

    var xhr = new XMLHttpRequest();
    xhr.onload = callback;
    xhr.open('POST', url);
    xhr.send(formData);

    }, type, quality);
};

// How to use it //

var form = document.querySelector('form'),   // the form to construct the FormData, can be null or undefined to send only the image
  url="http://example.com/upload.php",     // required, the url where we'll send it
  canvas = document.querySelector('canvas'), // required, the canvas to send
  filename = (new Date()).getTime() + '.jpg',// required, a filename
  type="image/jpeg",                       // optional, the algorithm to encode the canvas. If omitted defaults to 'image/png'
  quality = .5,                              // optional, if the type is set to jpeg, 0-1 parameter that sets the quality of the encoding
  callback = function(e) {console.log(this.response);}; // optional, a callback once the xhr finished

send(form, url, canvas, filename, type, quality, callback);

PHP side would then be :

if ( isset( $_FILES["file"] ) ){
    $dir="some/dir/";
    $blob = file_get_contents($_FILES["file"]['tmp_name']);
    file_put_contents($dir.$_FILES["file"]["name"], $blob);
    }

Leave a Comment