I'm trying to send some JSON data along with an image to the server. The image Blob
is coming from canvas' toBlob
method which I wrapped into a simple Promise
:
HTMLCanvasElement.prototype.toBlobPromise = function ( mimeType, qualityArgument ) {
let that = this;
return new Promise ( function ( resolve, reject ) {
that.toBlob ( function ( blob ) {
resolve ( blob );
}, mimeType, qualityArgument );
});
}
This seems to be working fine as I can see the Blob data in the console.
Here's the code where the issue occurs:
// preview is a canvas
// doc is an object literal
return preview.toBlobPromise ( 'image/png', 0.8 )
.then ( blob => {
let data = new FormData();
data.append( 'doc', JSON.stringify ( doc ) );
data.append( 'preview', blob );
// log all fields
for ( let field of data ) {
console.log ( field );
}
// at this point, both fields are logged correctly
// (2) ["doc", "{my JSON data}"]
// (2) ["preview", File(388719)]
return fetch ( 'save.php', {
body : data,
method : 'POST'
})
})
.then ( response => response.text() )
.then ( text => {
console.log ( text );
// here however, all I get is the 'doc' field
// array(1) {
// ["doc"]=> my JSON data
// }
})
On the server side save.php only contains var_dump ( $_POST )
.
As Patrick Evans said, the $_POST
superglobal does not contain files - they are stored in the $_FILES
superglobal.