Open main menu

How to Submit a File Uploads Form Using Ajax

Contents

A Simple Complete Example[edit]

We could use this sample code to upload the files selected by the user every time a new file selection is made.

<input type="file" id="file-input" multiple>


var files;
var fdata = new FormData();
$("#file-input").on("change", function (e) {
    files = this.files;

    $.each(files, function (i, file) {
        fdata.append("file" + i, file);
    });

    fdata.append("FullName", "John Doe");
    fdata.append("Gender", "Male");
    fdata.append("Age", "24");

    $.ajax({
        url: "/Test/Url",
        type: "post",
        data: fdata, //add the FormData object to the data parameter
        processData: false, //tell jquery not to process data
        contentType: false, //tell jquery not to set content-type
        success: function (response, status, jqxhr) {
            //handle success
        },
        error: function (jqxhr, status, errorMessage) {
            //handle error
        }
    });
});

Now let's break this down and inspect it part by part.

Working With File Inputs[edit]

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 properties allow for selecting more than one files, you can remove it if you want the user to select one file at a time.

<input type="file" id="file-input" multiple>

We will be using input's change event to capture the files.

var files;
$("#file-input").on("change", function(e){
    files = this.files;
});

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.

Creating and Filling the FormData[edit]

In order to upload files with Ajax, we are going to use FormData.

var fdata = new 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.

$.each(files, function(i, file) {
  //...
});

We will be using the append method of FormData to add the files into our form data object.

$.each(files, function(i, file) {
  fdata.append("file" + i, file);
});

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 information to our form data object.

fdata.append("FullName", "John Doe");
fdata.append("Gender", "Male");
fdata.append("Age", "24");
//...

Sending the Files With Ajax[edit]

$.ajax({
    url: "/Test/Url",
    type: "post",
    data: fdata, //add the FormData object to the data parameter
    processData: false, //tell jquery not to process data
    contentType: false, //tell jquery not to set content-type
    success: function (response, status, jqxhr) {
        //handle success
    },
    error: function (jqxhr, status, errorMessage) {
        //handle error
    }
});

We set processData and contentType properties to false. This is done so that the files can be sent to the server and be processed by the server correctly.