When I upload a file the normal way without Ajax, the page reloads, and the POST request payload looks like this when I look at it in the network tab of the Chrome element inspector:
------WebKitFormBoundaryXseUYiNOVZKdYrTk
Content-Disposition: form-data; name="fdata[]"; filename="baby_bot.jpg"
Content-Type: image/jpeg
------WebKitFormBoundaryXseUYiNOVZKdYrTk
Content-Disposition: form-data; name="fdata[]"; filename="dyno_bones.png"
Content-Type: image/png
------WebKitFormBoundaryXseUYiNOVZKdYrTk--
But when I try to create the POST request manually and send the file with ajax by using the FileReader object to read the content of a file in binary format and sending the binary data via the manually created POST request, the payload looks like this in the inspector:
------CustomFormBoundaryXseUYiNOVZKdYrTk
Content-Disposition: form-data; name="fdata[]"; filename="baby_bot.jpg"
Content-Type: image/jpeg
a2q#¡B±Áð$RÑá3ñ%br4C&Scs¢ÂâÿÄ
------CustomFormBoundaryXseUYiNOVZKdYrTk
Content-Disposition: form-data; name="fdata[]"; filename="dyno_bones.png"
Content-Type: image/png
a2q#¡B±Áð$RÑá3ñ%br4C&Scs¢ÂâÿÄ
------CustomFormBoundaryXseUYiNOVZKdYrTk--
Notice that you can see the binary data (represented by those random accented characters) when in the body of the POST request. How can I make my manually created POST request be perfectly identical to that of the browser so that the I get identical results from my PHP handler script? The idea here is that I can emulate the POST requests that the browser sends and not have to modify anything in the PHP backend.
Instead of trying to emulate the POST request data, use the
FormDataobject. Its easy to use and lets you send form data via ajax easily. AFormDataobject automatically creates and send the appropriate POST request with the help of anXMLHttpRequestobject.The Mozilla documentation includes a nice article on how to use the XMLHttpRequest object which itself includes a nice example on how to use the FormData object.