[英]Javascript XHR send multipart/form-data
I'm trying to send a multipart/form-data content-type request: 我正在尝试发送multipart / form-data内容类型请求:
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 $_POST
array 然后在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? 我究竟做错了什么?
Your code failed because you've used "Enter" instead of an escaped line break character ( \\n
). 您的代码失败,因为您使用了“Enter”而不是转义的换行符( \\n
)。
JavaScript doesn't support "first line[Enter]second line"
. JavaScript不支持"first line[Enter]second line"
。 If you need a string with a line break, use "first line\\nsecond 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, not binary data. 注意 :您的代码仅适用于由UTF-8字符组成的有效负载, 而不是二进制数据。 If you want to learn more about submitting forms with binary data via XMLHttpRequest, see this answer and its linked references. 如果您想了解有关通过XMLHttpRequest提交包含二进制数据的表单的更多信息,请参阅此答案及其链接引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.