Using FormData object, the server receives an empty POST

China☆狼群 提交于 2019-12-19 10:09:00

问题


I'm attempting to send one file and one text variable to my server with the FormData object. Looking at the Network tab in Chrome's developer tools, I can see that the file and variable are being sent. However, I've tried var_dump() on the $_POST and $_FILES variables, and both are shown as empty arrays. Here's the code I'm using for the form:

var image_upload = document.getElementById("image_upload");

if(image_upload.value == '')
{
   alert("Please select a file to upload.");
}
else
{
   alert("in");
   var ajaxHandler = new XMLHttpRequest();
   var content = image_upload.files[0];
   var formData = new FormData();
   formData.append("type", "5");
   formData.append("content", content)

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

   ajaxHandler.open("POST", "newCard", false);
   ajaxHandler.setRequestHeader("Content-type","multipart/form-data");
   ajaxHandler.send(formData);
}

I have tried this code with and without "charset=utf-8" in the content type, and it doesn't seem to make a difference. What's going on here?


回答1:


Remove the ajaxHandler.setRequestHeader("Content-type","multipart/form-data"); from the code. The proper multipart/form-data header should contain boundary string. Browser automatically set that header, if you add file in FormData.



来源:https://stackoverflow.com/questions/10326955/using-formdata-object-the-server-receives-an-empty-post

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