How to Submit a File Uploads Form Using Ajax

Contents

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

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

varfiles;varfdata=newFormData();$("#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 parameterprocessData:false,//tell jquery not to process datacontentType:false,//tell jquery not to set content-typesuccess:function(response,status,jqxhr){//handle success},error:function(jqxhr,status,errorMessage){//handle error}});});

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.

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.

$.ajax({url:"/Test/Url",type:"post",data:fdata,//add the FormData object to the data parameterprocessData:false,//tell jquery not to process datacontentType:false,//tell jquery not to set content-typesuccess: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.