Ajax file upload with jQuery and Asp.Net MVC

In this article, I’ll try to give an example for file upload with using jQuery to a ASP.NET MVC controller.

Step 1: Creating Web Application

I’m going start working on our controller.

To create a simple MVC project:

  1. Open Visual Studio
  2. Click “New Project” and select “ASP.NET Web Application”
  3. Select empty project and click to MVC then click Ok.

Thats it! We have an empty mvc project. Right click to “controllers” on “Solution Explorer” tab. Click “Add” then “Controller” and name it as “Home”.

public class HomeController : Controller
{
   //
   // GET: /File/
   public ActionResult Index()
   {
        return View();
   }
}

We need a page for upload process so right click to somewhere of Index method then click to “Add View”. Uncheck “Use a layout page” then click to Add.
We wont work on this page until our controller prepared.

Now we can create a method which will handle process when client sent its upload request to server.

Simply add this method below Index.

 public JsonResult UploadFile(HttpPostedFileBase file)
 {
     var result = DoSomethingWithFile(file);
     return Json(result, JsonRequestBehavior.AllowGet);
 }

 

What is HttpPostedFileBase class? 
This is the base class for classes that provide access to individual files that have been uploaded by a client. For more detail check MSDN

What is JsonRequestBehavior?
Specifies wheter HTTP Get requests from clients.

 

We have declared a “result” variable in UploadFile method. With this, we will tell to client to what happened to his file. Saved or not. Simple.

Now we will prepare DoSomethingWithFile method.

Add following code to controller

private bool DoSomethingWithFile(HttpPostedFileBase file)
{
  try
  {
       var strFileLocation = "/temp/" + file.FileName;
       file.SaveAs(HttpContext.Server.MapPath(strFileLocation));
       return true;
  }
  catch (Exception)
  {
      return false;
  }
}

By the way we need to add a temp folder to save files. Rgiht click to project name and click “Add” then “Folder”. Name it as “temp”.

We are done with server side right now. Lets get started on our web page.

 

Step 2: Creating Page

Click to Views – File then Index.cshtml file from solution explorer.

Here we go.

Add jQuery library to page by following to head  tag:

<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>

I’m going to use standart file input but we need a little trick here :)First of all we need a button and an input element to send file to server.

I’m going to create them into a container. You can put them anywhere you want of course 🙂

<button id="btn-upload">Send File</button>
<input type="file" id="file-uploader" />

If you want to create a custom design for upload which I preffer we need to trigger choose file event via jquery.

Usually a choose file event only triggered by inputs “choose file” button when its clicked. Let’s change the css of file input and make its width and height as 0. Also i’ll give some style to our button.

<style>
.upload-container {
   margin-left: auto;
   margin-right: auto;
   width: 125px;
   height: 35px;
   margin-top: 20%;
   background-color: #ccc;
   padding: 10px;
   -moz-border-radius: 4px;
   -webkit-border-radius: 4px;
   border-radius: 4px;
 }
#btn-upload{
   width: 125px;
   padding-top: 10px;
   padding-bottom: 10px;
   border: none;
   text-align: center;
   background-color: rgb(113, 157, 163);
   color: white;
   -moz-border-radius: 4px;
   -webkit-border-radius: 4px;
   border-radius: 4px;
   line-height: 100%;
   cursor: pointer;
}
#file-uploader{
   width:0px;
}
</style>

We need to trigger choose file event when user clicks to our button. So to do this we need a jQuery script.

Let’s work on it.

<script type="text/javascript">
$(function () {
    $("#btn-upload").on("click", function () {
    $('#file-uploader').click();
  });
});
</script>

Quite simple isnt it?
We picked our file to upload. Whats next?

I want to send file to server after choosing a file. So we need to improve jquery code with few lines to add more functionality to “Change” event of file input.

<script type="text/javascript">
$(function () {
    $("#btn-upload").on("click", function () {
    $('#file-uploader').click();
  });
});
$(function () {
   $("#imageFile").on("change", function () {
   SubmitFile(); //This is going to be our upload function.
 });
});
</script>

Now our ajax post will only work when file input change event triggered. I mean user chooses a file upload to server.

Let’s create a function for to send file to server.

<script type="text/javascript">
$(function () {
    $("#btn-upload").on("click", function () {
    $('#file-uploader').click();
  });
});
$(function () {
   $("#file-uploader").on("change", function () {
   SubmitFile(); //This is our upload function.
 });
});
function SubmitFile() {
 var formData = new FormData(); //We need to create form. Beause we are sending a file here!
 var file = document.getElementById("file-uploader").files[0]; //file

 formData.append("file", file); //Added file to our form

 $.ajax({
    type: "POST",
    url: '@Url.Action("UploadFile","Home")', //Name of action and controller
    data: formData,
    dataType: 'json',
    contentType: false,
    processData: false,
    beforeSend: function () {
    //this event is unneccesary. You can use it for a loader. Triggers before sending data.
    $("#btn-upload").text("Uploading");
    },
    success: function () {
    //this event unneccesary too. I prefer to use it for showing a dialog to tell user "Hey, It's uploaded!"
    //Success doesnt mean file saved on server. It means only post succeed.
    $("#btn-upload").text('Hey, Its uploaded!');
    }
 });
}
</script>

Now we created our page.

 

Go head and run the project.

Summary

This is a simple uploader but its easy modify for more features like mutliple file upload or add a loader animation.

Sample project available on my Git

 

 

 

 

 

 

 

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *