How to Upload Files Asynchronously using ASP.NET MVC4 application.


Introduction

In this post, I explain how to upload files asynchronously using ASP.NET MVC4 application with progress bar.
Uploading files to the web server is a very common operation. By default, this file upload process is synchronous, you can see how to upload file (synchronous) in asp.net MVC. But, there is no any default control for asp.net developer for upload file on the server in an asynchronous manner.Here in this example we will see how we can easily upload files on the server in an asynchronous manner.



Steps :

Step - 1: Create New Project.

Go to File > New > Project > Select asp.net MVC4 web application > Entry Application Name > Click OK > Select Internet Application > Select view engine Razor > OK

Step-2: Add a new Controller.

Go to Solution Explorer > Right Click on Controllers folder form Solution Explorer > Add > Controller > Enter Controller name > Select Templete "empty MVC Controller"> Add.

Step-3: Add new action into your controller for Get Method.

Here I have added "AsyncUpload" Action into "Upload" Controller. Please write this following code

public ActionResult AsyncUpload()
{
    return View();
}

Step-4: Add view for the Action & design.

Right Click on Action Method (here right click on form action) > Add View... > Enter View Name > Select View Engine (Razor) > Check "Create a strong-typed view" > Select your model class > Add.

Step-5: Add jQuery code for upload file to the server.

Jquery Code
 <script src="http://malsup.github.com/jquery.form.js"></script>
  <script>
  (function () {
  var bar = $('.progress-bar');
  var percent = $('.progress-bar');
  var status = $('#status');

  $('form').ajaxForm({
  beforeSend: function () {
  status.empty();
  var percentValue = '0%';
  bar.width(percentValue);
  percent.html(percentValue);
  },
  uploadProgress: function (event, position, total, percentComplete) {
  var percentValue = percentComplete + '%';
  bar.width(percentValue);
  percent.html(percentValue);
  },
  success: function (d) {
  var percentValue = '100%';
  bar.width(percentValue);
  percent.html(percentValue);
  $('#fu1').val('');
  alert(d);
  },
  complete: function (xhr) {
  status.html(xhr.responseText);
  }
  });
  })();
  </script>
  
Complete View
 @{
  ViewBag.Title = "Async File Upload";
  }

  <h2>Async File Upload</h2>

  @using (Ajax.BeginForm("AsyncUpload", "Upload", new AjaxOptions() { HttpMethod = "POST" }, new { enctype="multipart/form-data"}))
  {
  @Html.AntiForgeryToken()
  <input type="file" name="files" id="fu1"/>
  <input type="submit" value="Upload File" />
  
  }

  <div class="progress">
  <div class="progress-bar">0%</div>
  </div>
  <div id="status"></div>
  <style>
  .progress {
  position:relative; 
  width:400px;
  border:1px solid #ddd;
  padding:1px;
  }
  .progress-bar {
  width:0px;
  height:20px;
  background-color:#57be65;
  }
  </style>
  @section scripts{
  <script src="http://malsup.github.com/jquery.form.js"></script>
  <script>
  (function () {
  var bar = $('.progress-bar');
  var percent = $('.progress-bar');
  var status = $('#status');

  $('form').ajaxForm({
  beforeSend: function () {
  status.empty();
  var percentValue = '0%';
  bar.width(percentValue);
  percent.html(percentValue);
  },
  uploadProgress: function (event, position, total, percentComplete) {
  var percentValue = percentComplete + '%';
  bar.width(percentValue);
  percent.html(percentValue);
  },
  success: function (d) {
  var percentValue = '100%';
  bar.width(percentValue);
  percent.html(percentValue);
  $('#fu1').val('');
  alert(d);
  },
  complete: function (xhr) {
  status.html(xhr.responseText);
  }
  });
  })();
  </script>
  }
  

Step-6: Add another action into your controller for Upload files to the server.

Here I have added "AsyncUpload" Action into "Upload" Controller for POST Action. Please write this following code

 [HttpPost]
  [ValidateAntiForgeryToken]
  public ActionResult AsyncUpload(IEnumerable<HttpPostedFileBase> files)
  {
  int count = 0;
  if (files != null)
  {
  foreach (var file in files)
  {
  if (file != null && file.ContentLength > 0)
  {
  var fileName = Guid.NewGuid() + Path.GetExtension(file.FileName);
  var path = Path.Combine(Server.MapPath("~/UploadedFiles"), fileName);
  file.SaveAs(path);
  count++;
  }
  }
  }
  return new JsonResult { Data = "Successfully " + count+ " file(s) uploaded" };
  }
  

Step-7: Create a folder for Save uploaded files.

Right Click on ProjectName under Solution Explorer > Add > New Folder > enter folder name.

Step-8: Run Application.


 How to Upload Files Asynchronously using ASP.NET MVC4 application.

Hello ! My name is Sourav Mondal. I am a software developer working in Microsoft .NET technologies since 2010.

I like to share my working experience, research and knowledge through my site.

I love developing applications in Microsoft Technologies including Asp.Net webforms, mvc, winforms, c#.net, sql server, entity framework, Ajax, Jquery, web api, web service and more.