How to use FormData for AJAX file upload?
For an AJAX file upload, initialize FormData to collect your data, add() your file, then send it all packing with XMLHttpRequest
:
In this simple version, replace 'upload_url'
with the exact path of your server's upload endpoint. Houston, we are smooth sailing, no page reloads required.
Packing the truck: Dealing with multiple files & data types
Sometimes one is not enough. You've got a fleet of files, input fields with additional data. So let's loop:
Just like loading up the Millennium Falcon, every piece of cargo (file or other data type) has its place ready in the FormData
object.
Supercharging our droid: Enhancing the AJAX request
Why contentType: false
? It stops jQuery from declaring application/x-www-form-urlencoded
to all. processData: false
keeps jQuery from mulling over the FormData
object.
Compatibility and progress reporting
To use the contentType: false
set up, ensure jQuery 1.6 or newer. After sending R2 off, wouldn't you like to know his progress? Well, the droid can communicate it back:
May the network be with you
Some times traffic jams can happen in the most remote galaxies. A timeout fallback will allow the Force to be with you, always.
On timeout or network disturbance, implement a retry mechanism, or a kindly "Server is down, young Padawan."
Sith-proofing the server
The Dark Side is always there, lurking. Secure your file handling server-side by validating file types, sizes, and watches for the Imperial Walker attack (a multitude of simultaneous uploads). Always authenticate inputs, the Sith move among us.
Was this article helpful?