使用XMLHttprequest上传文件 - 在multipart / form-data中缺少边界 [英] Uploading a file with XMLHttprequest - Missing boundary in multipart/form-data
问题描述
我正在使用XMLHttprequest上传文件。
这是上传文件的JS函数:
var upload = function(file){
//创建表单数据
var formData = new FormData();
formData.append('file',file);
var xhr = new XMLHttpRequest();
//打开
xhr.open('POST',this.options.action);
//设置头文件
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);
//发送
xhr.send(formData);
}
在服务器端, upload.php 我用这种方式读取文件:
file_put_contents($ filename,(file_get_contents('php:// input')));
一切正常,但我收到PHP警告:
多行/表格数据中缺少边界0行中未知的POST数据
。
如果我删除这一行:
xhr.setRequestHeader(Content-Type,multipart / form-data);
警告消失。
这里应该出现什么问题?
这有点奇怪了对我而言,但这是有用的:
//打开
xhr.open('POST',这个.options.action,true);
// !!! REMOVED ALL HEADERS
//发送
xhr.send(formData);
在这种情况下,在服务器端我不读取通过 php://输入
但文件将在 $ _ FILES
数组中。
<这解决了我的问题,但我仍然很好奇为什么现在出现
$ _ FILES
中的文件? 在Chrome,Mozilla,Safari和IE10中测试过。
I'm uploading a file with XMLHttprequest. Here is the JS function, that uploads a file:
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:
file_put_contents($filename, (file_get_contents('php://input')));
Everything works fine, except that I get a PHP Warning:
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");
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.
This solved my problem, but I'm still curious why appears now the file in $_FILES
?
Tested in Chrome, Mozilla, Safari, and IE10.
这篇关于使用XMLHttprequest上传文件 - 在multipart / form-data中缺少边界的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!