Javascript 使用 XMLHttprequest 上传文件 - multipart/form-data 中缺少边界

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12348216/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:46:48  来源:igfitidea点击:

Uploading a file with XMLHttprequest - Missing boundary in multipart/form-data

phpjavascriptxmlhttprequestxmlhttprequest-level2

提问by Tamás Pap

I'm uploading a file with XMLHttprequest. Here is the JS function, that uploads a file:

我正在使用 XMLHttprequest 上传文件。这是上传文件的 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.phpI 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");the warning goes away.

如果我删除此行: xhr.setRequestHeader("Content-Type", "multipart/form-data");警告消失。

What should be the problem here?

这里应该是什么问题?

回答by Tamás Pap

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://inputbut the file will be in the $_FILESarray.

在这种情况下,在服务器端我不读取通过发送的文件,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 中测试。