Jquery Ajax File Uploads
1. A Simple Complete Example
We could use this sample code to upload the files selected by the user every time a new file selection is made.
Now let's break this down and inspect it part by part.
2. Working With File Inputs
This MDN Document ( Using files from web applications ) is a good read about various methods on how to handle file inputs. Some of these methods will also be used in this example.
Before we get to uploading files, we first need to give the user a way to select the files they want to upload. For this purpose we will use a file input. The multiple property allows for selecting more than one files, you can remove it if you want the user to select one file at a time.
Inside the handler function, we access the files through the files property of our input. This gives us a FileList, which is an array like object.
3. Creating and Filling the FormData
In order to upload files with Ajax we are going to use FormData.
FileList we have obtained in the previous step is an array like object and can be iterated using various methods including for loop, for...of loop and jQuery.each. We will be sticking with the jQuery in this example.
We will be using the append method of FormData to add the files into our formdata object.
We can also add other data we want to send the same way. Let's say we want to send some personal information we have received from the user along with the files. We could add this this information into our formdata object.
4. Sending the Files With Ajax
We set processData and contentType properties to false. This is done so that the files can be send to the server and be processed by the server correctly.