javascript 如何在使用 XmlHttpRequest 和 FormData 时设置边界

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

How to set boundary while using XmlHttpRequest and FormData

javascriptajaxforms

提问by Ankit

I am trying to set the boundary correctly in the header while using FormData to post the XmlHttpRequest:

我试图在使用 FormData 发布 XmlHttpRequest 时在标头中正确设置边界:

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

var formData = new FormData();
formData.append("filename", inputId.files[0]);
formData.append(...);

xhr.send(formData);

How do I get the boundary to be set in the request header here. I saw the request being set, the boundary is somehow created in the request. But the server has no idea on how to interpret it.

如何在此处的请求标头中设置边界。我看到请求被设置,边界以某种方式在请求中创建。但是服务器不知道如何解释它。

回答by Anton Morozov

ES method

ES法

Simply don't set the Content-Type header manually and the browser will automatically set "multipart/form-data; boundary=..." value.

只需不要手动设置 Content-Type 标头,浏览器将自动设置“multipart/form-data;boundary=...”值。



jQuery method

jQuery 方法

If you're using jQuery, set contentType option to false:

如果您使用 jQuery,请将 contentType 选项设置为 false:

$.ajax({
    url: url,
    type: 'POST',
    data: formData,
    processData: false,
    contentType: false
});

回答by Mark Giblin

Try looking at this, How to send multipart/form-data form content by ajax (no jquery)?I am trying to work with this script with PHP as the reciever, having some problems with mixed results of warnings and I think my problem is that I have hacked away at the scripts both ends too much that its no longer functioning.

试试看这个,How to send multipart/form-data form content by ajax (no jquery)? 我正在尝试使用 PHP 作为接收器使用此脚本,但在警告混合结果方面遇到了一些问题,我认为我的问题是我对脚本两端的攻击太多,以至于它不再起作用。

As for the comment by the other poster "If you're using JQuery", the only thing I have to say to that comment is that it is not helpful to the person not working in JQuery and JQ is not the be all and end all of scripts.

至于另一张海报“如果你使用 JQuery”的评论,我唯一要说的是,这对不在 JQuery 中工作的人没有帮助,而且 JQ 并不是全部和结束的脚本。