[英]Uploading a file with XMLHttprequest - Missing boundary in multipart/form-data
I'm uploading a file with XMLHttprequest. 我正在使用XMLHttprequest上传文件。 Here is the JS function, that uploads a file:
这是JS函数,它上传文件:
var upload = function(file) {
// Create form data
var formData = new FormData();
formData.append('file', file);
var xhr = new XMLHttpRequest();
// Open
xhr.open('POST', this.options.action);
// Set headers
xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.setRequestHeader("X-File-Name", file.fileName);
xhr.setRequestHeader("X-File-Size", file.fileSize);
xhr.setRequestHeader("X-File-Type", file.type);
// Send
xhr.send(formData);
}
On the server side, in upload.php I read the file this way: 在服务器端,在upload.php中我以这种方式读取文件:
file_put_contents($filename, (file_get_contents('php://input')));
Everything works fine, except that I get a PHP Warning: 一切正常,除了我得到一个PHP警告:
Missing boundary in multipart/form-data POST data in Unknown on line 0
. Missing boundary in multipart/form-data POST data in Unknown on line 0
。
If I remove this line: xhr.setRequestHeader("Content-Type", "multipart/form-data");
如果我删除这一行:
xhr.setRequestHeader("Content-Type", "multipart/form-data");
the warning goes away. 警告消失了。
What should be the problem here? 这应该是什么问题?
Well this is strange a little bit for me, but this is what worked: 嗯这对我来说有点奇怪,但这是有效的:
// Open
xhr.open('POST', this.options.action, true);
// !!! REMOVED ALL HEADERS
// Send
xhr.send(formData);
In this case, on server side I don't read the file sent via php://input
but the file will be in the $_FILES
array. 在这种情况下,在服务器端我不读取通过
php://input
发送的文件,但该文件将在$_FILES
数组中。
This solved my problem, but I'm still curious why appears now the file in $_FILES
? 这解决了我的问题,但我仍然很好奇为什么现在出现在
$_FILES
的文件?
Tested in Chrome, Mozilla, Safari, and IE10. 在Chrome,Mozilla,Safari和IE10中测试过。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.