Ajax JS / PHP Image Uploader not working

I tried several approaches and asked quite a few questions in StkOvfl and W3 specifications, but still do not know.

I have form input:

<input type="file" multiple accept="image/*" id="item-image-upload" > 

Then in my Javascript method ( prepareFormData ): [See full gist class here] :

  var files = this.getFiles(); var formData = new FormData(); for (var i = 0; i < files.length; i++) { var file = files[i]; if (!file.type.match('image.*')) { continue; } formData.append(this.uploadEntityName, file); } 

When I console.log(files), I get all the files in order. But formData is not working. I also tried adding an arbitrary element like:

  formData.append("Apple", 1); 

The answer I get is empty. The server works in php as:

 public function uploadImage(){ return json_encode(array_merge($_REQUEST, $_FILES)); } 
+6
source share
1 answer

I'm 99% sure that now this is your headline, and if you look in your logs or enable PHP Warnings, you will see Warning: Missing boundary in multipart/form-data POST data in Unknown on line 0

I copied this (and added your header line and deleted the input file) from MDN and ran it on a script on my dev that is configured to cry all errors, and I got this error, followed by an empty array

 var formData = new FormData(); formData.append("username", "Groucho"); formData.append("accountnum", 123456); // number 123456 is immediately converted to a string "123456" // JavaScript file-like object var content = '<a id="a"><b id="b">hey!</b></a>'; // the body of the new file... var blob = new Blob([content], { type: "text/xml"}); formData.append("somefiles[]", blob); var request = new XMLHttpRequest(); request.open("POST", "MYDEVBOX/testpost.php"); // remove the line below and it works request.setRequestHeader("Content-Type", "multipart/form-data"); request.responseType = "json"; request.send(formData); 

We will be back a few minutes after deciding why. This is due to the data boundary with several parts. XHR automatically sets the header with the appropriate border when you execute xhr.send(formData) (or somewhere along the way). When you set this header, the query uses this instead, destroying the border, and PHP doesn't know where to split the input. Here is a quick screen cover that shows it much better.

enter image description here

+4
source

All Articles