Ajax file upload

ajax file upload

With the latest browser from Safari 5/Firefox 4 we can use FormData class:

So now we have a object of FormData , which can be sent along with the XMLHttpRequest.

 

We can  set the contentType option to false,which  force jQuery not to add a Content-Type header for you, otherwise, the boundary string will be missing from it. Also, we must leave the processData flag set to false, otherwise, jQuery will try to convert your FormData into a string, which will fail.

Now we can  retrieve the file in PHP using:

This is just for a single file .If you have multiple files, the numbers (file-n) will increment with each file

For older browsers we can use FormData emulation 

Creating  FormData from an existing form

Instead of manually iterating the files, the FormData object can also be created with the contents of an existing form object:

Use a PHP native array instead of a counter

Just name your file elements the same and end the name in brackets:

$_FILES['file'] will then be an array containing the file upload fields for every file uploaded. I actually recommend this over my initial solution as it’s simpler to iterate over.

Comments

comments