The Client-Side Part
1. File Uploading Using a Plain HTML File Input With a Submit Button
Everyone knows a good old file input with a submit button inside a form:
It doesn’t work better than it looks: you need to click the submit button after a file is selected and your page will be reloaded. But it works everywhere. HTML is simple (multiple attribute allows the file input to select and upload more than one file at the same time):
2. File Uploading Using a Plain HTML File Input Without a Submit Button
3. File Uploading Using a Plain HTML File Input With a Custom UI and Without a Submit Button
Option 2 is a bit better than option 1, but the file input still looks ugly. It is possible to apply some CSS to change its appearance to something like this:
Here we have made the file input huge and transparent, and put it inside the container with the label. The label ignores mouse events, so our invisible file input is able to receive them. This approach has good enough support and is widely used. Also, it is possible to display the names of the selected files if you need that. But it still reloads the page.
4. File Uploading Using an IFrame with a Plain HTML File Input With a Custom UI and Without a Submit Button
To use this method we need to add the iframe to our page:
5. File Uploading Using a Plain HTML File Input With a Custom UI and jQuery.ajax() Function
To test the file input approach we need to modify HTML from the option 3 a bit (the only thing we have to change is onchange attribute of the file input):
As you can see, onchange attribute of the file input contains the uploadFiles function call now (instead of the submitForm one). This function takes the files selected by a user and uploads them to a server using the jQuery.ajax() function:
Please note how we get the files from the file input and then combine them into a single FormData object. This is really good approach, the only problem is that it doesn’t have so perfect browsers support like options 1, 2, 3 and 4.
6. File Uploading Using the Drag and Drop feature and jQuery.ajax() Function
The difference is only in the way of getting the files. Now we use event.dataTransfer.files instead of input.files from the previous option.
The Server-Side Part
The important thing is that the server-side part is the same for all of the examples in this article. And it is quite simple:
As you can see, action receives the list of the uploaded files and simply saves them.
Using the options 5 and 6 where it is possible probably is the best choice because they provide better user experience. At the same time, options 3 and 4 has better browsers support and might be used where compatibility with older browsers is important.
I have created the demo project for this post. Feel free to ask if you have any questions!