Javascript XHR 发送多部分/表单数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20730489/
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-10-27 19:09:09  来源:igfitidea点击:

Javascript XHR send multipart/form-data

javascriptxmlhttprequestmultipartform-data

提问by php_nub_qq

I'm trying to send a multipart/form-data content-type request:

我正在尝试发送多部分/表单数据内容类型请求:

var xhr = new XMLHttpRequest();

xhr.onreadystatechange = function(){
    if(xhr.readyState==4){
         alert(xhr.responseText);
    }
}

xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type","multipart/form-data; boundary=---------------------------275932272513031");

xhr.send('-----------------------------275932272513031 Content-Disposition: form-data; name="name"

test

----------------------------275932272513031--');

Then in php I just print the $_POSTarray

然后在php中我只打印$_POST数组

print_r($_POST);

But I get an empty array each time. I expect to see

但我每次都会得到一个空数组。我期待看到

Array (
    name => "test"
)

What am I doing wrong?

我究竟做错了什么?

回答by Rob W

Your code failed because you've used "Enter" instead of an escaped line break character (\n).
JavaScript doesn't support "first line[Enter]second line". If you need a string with a line break, use "first line\nsecond line".

您的代码失败,因为您使用了“Enter”而不是转义的换行符 ( \n)。
JavaScript 不支持"first line[Enter]second line". 如果您需要带换行符的字符串,请使用"first line\nsecond line".

Once you've fixed this problem, your code should work as intended (with one caveat, see final note):

一旦你解决了这个问题,你的代码应该可以按预期工作(有一个警告,请参阅最后的注释):

var xhr = new XMLHttpRequest();
xhr.onload = function() {
     alert(xhr.responseText);
};
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type","multipart/form-data; boundary=---------------------------275932272513031");
xhr.send('-----------------------------275932272513031\n' +
         'Content-Disposition: form-data; name="name"\n\n' +
         'test\n\n' +
         '----------------------------275932272513031--');

NOTE: Your code will only work for payloads that consists of UTF-8 characters, notbinary data. If you want to learn more about submitting forms with binary data via XMLHttpRequest, see this answerand its linked references.

注意:您的代码仅适用于由 UTF-8 字符组成的有效负载,而不适用于二进制数据。如果您想了解有关通过 XMLHttpRequest 提交带有二进制数据的表单的更多信息,请参阅此答案及其链接的参考资料。