发送到服务器后,FormData 缺少带有 Blob 的字段
FormData missing a field with Blob once sent to the server
我正在尝试将一些 JSON 数据连同图像一起发送到服务器。图片 Blob
来自 canvas' toBlob
方法,我将其包装成一个简单的 Promise
:
HTMLCanvasElement.prototype.toBlobPromise = function ( mimeType, qualityArgument ) {
let that = this;
return new Promise ( function ( resolve, reject ) {
that.toBlob ( function ( blob ) {
resolve ( blob );
}, mimeType, qualityArgument );
});
}
这似乎工作正常,因为我可以在控制台中看到 Blob 数据。
这是出现问题的代码:
// 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
// }
})
服务器端save.php只包含var_dump ( $_POST )
.
正如 Patrick Evans 所说,$_POST
超全局不包含文件 - 它们存储在 $_FILES
超全局中。
我正在尝试将一些 JSON 数据连同图像一起发送到服务器。图片 Blob
来自 canvas' toBlob
方法,我将其包装成一个简单的 Promise
:
HTMLCanvasElement.prototype.toBlobPromise = function ( mimeType, qualityArgument ) {
let that = this;
return new Promise ( function ( resolve, reject ) {
that.toBlob ( function ( blob ) {
resolve ( blob );
}, mimeType, qualityArgument );
});
}
这似乎工作正常,因为我可以在控制台中看到 Blob 数据。
这是出现问题的代码:
// 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
// }
})
服务器端save.php只包含var_dump ( $_POST )
.
正如 Patrick Evans 所说,$_POST
超全局不包含文件 - 它们存储在 $_FILES
超全局中。