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.

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:

[HttpPost]
public string Upload(HttpPostedFileBase file)
{
var jss=new JavaScriptSerializer();
try
{
if (file.ContentLength > 0)
{
//Get file name
var fileName = Path.GetFileName(file.FileName);
//Specify the path for saving
var path = Path.Combine(Server.MapPath("~/UploadedFiles"), fileName);
//Save the file
file.SaveAs(path);
}
return jss.Serialize("Uploaded successfully!");
}
catch (Exception)
{
return jss.Serialize("Sorry, an error occurred");
}

}

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.

You can download jQuery.upload plugin here.

Now,let’s add our jQuery code to the page:

$(document).ready(function () {
var uploadTextbox = $('#uploadFile');
var message = $('#message');
$('#uploadButton').click(function () {
message.text('');
LoaderShow();
uploadTextbox.upload('Home/Upload', function (result) {
LoaderHide();
message.append(result);
uploadTextbox.val('');
}, 'json');
});
});

function LoaderHide() {
$('#ajaxLoader').css('display','none');
}
function LoaderShow() {
$('#ajaxLoader').css('display', 'block');
}

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!

Advertisements

2 thoughts on “ASP.NET MVC file upload using jQuery

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s