Send XMLHttpRequest with both Header and FormData

谁说胖子不能爱 提交于 2019-12-02 10:31:32

问题


I am trying to send a XMLHttpRequest with a header and add a FormData. Is there an (elegant) way i can do something like this:

var formData = new FormData();
formData.append("file", file);
var xhr = new XMLHttpRequest();

xhr.open("POST", "/ajax_gateway.php?mod=fileupload", true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded")
xhr.send(formData, "token=add");

回答1:


You cannot specify the Content-Type header when sending FormData because that header automatically gets set to "multipart/form-data" by the browser. You can set other headers though, try this:

var formData = new FormData();
formData.append("file", file);
formData.append("mod", "fileupload");
formData.append("token", "add");

var xhr = new XMLHttpRequest();
xhr.open("POST", "/ajax_gateway.php");
xhr.setRequestHeader("X-Answer", "42");
xhr.send(formData);


来源:https://stackoverflow.com/questions/23802133/send-xmlhttprequest-with-both-header-and-formdata

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!