Developer's blog

Main menu

ASP.NET MVC file upload using jQuery

In this post I’d like to show you how to make ajax file uploading using jQuery.
There are plenty of jQuery plugins on the internet, which can help us to solve this problem and some times it’s too complicated to choose the appropriate one.

I’ve surfed the internet and found simple plugin which called jQuery.upload. It’s simple ajax file upload plugin.
It’s very ease to use it. The file is uploaded asyncronously by posting data to the iframe generated in the same page.
The callback function when uploading is completed can be specified, and the data of the form specified by the fourth argument is received.
It’s important to know that all the fields are sent when the specified element has two or more fields in the descendant element.
The method can be called by the following form:
upload(url, [data], [callback], [type])

I’m going to use asp.net mvc at the server side to show you how this works.
So, let’s start
Firstly, create ASP.NET MVC project with standard structure using visual studio.

At the Home.cshtml let’s add the following mark-up.

Loading...

Here we added input for file uploading, button, simple loader, which will appear while uploading a file.
If the file uploads successfully, the user will see the message.

Good. Now we should add some code in the controller. In HomeController we’ll add the following action method:

Notice, that in controller, we used HttpPostedFileBase class, the base class for classes that provide access to individual files that have been uploaded by a client.
In other words, this action gets an HttpPostedFileBase object containing properties for the original local filename and the content of the file itself.
Also, we add [POST] attribute to our action, so now it will invoke only if post request took place.
In addition I used javaScriptSerializer class, that provides serialization and deserialization functionality.
But, of course, it’s not necessarily to use it for displaying message to the client:)

Nearly done. Now, we’ll add some jQuwery code to our view to use plugin.
At the beginning, we must include our plugin to the project. Just add script refererence to the page.

In this code we just invoke ajax uploader when the user clicks upload button.
The parameters which upload function accepts are url and callback function if seccess takes place.
Also I’ve addded two functions which show and hide div with loader .gif image.
That’s all.Enjoy using it!