File Upload In WEBAPI Using JQuery

Welcome to the next part of tutorial in Web API series. In this post, I am going to explain, how to upload the files, using Web API help of jquery. If you are new to Web API in ASP.NET MVC5. Refer below the posts for the basics of Web API.

  • Introduction to Web API.
  • How to retrieve and display the data from Web API in ASP.NET MVC5.
  • How to post the data to Web API, using jQuery client.

Create an API Service to save the uploaded file in the Server

  1. I created a UploadapiController API controller.
  2. Add a new folder "UploadFiles" folder to the solution.
  3. Replace the UploadapiControlller code with the code, given below, to save the uploaded file.
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.IO;  
    4. using System.Linq;  
    5. using System.Net;  
    6. using System.Net.Http;  
    7. using System.Threading.Tasks;  
    8. using System.Web;  
    9. using System.Web.Http;  
    10. namespace WebApiExample.Controllers {  
    11.     public class UploadapiController: ApiController {  
    12.         public Task Post() {  
    13.             List savedFilePath = new List();  
    14.             if (!Request.Content.IsMimeMultipartContent()) {  
    15.                 throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);  
    16.             }  
    17.             string rootPath = HttpContext.Current.Server.MapPath("~/UploadedFiles");  
    18.             var provider = new MultipartFileStreamProvider(rootPath);  
    19.             var task = Request.Content.ReadAsMultipartAsync(provider).  
    20.             ContinueWith(t => {  
    21.                 if (t.IsCanceled || t.IsFaulted) {  
    22.                     Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);  
    23.                 }  
    24.                 foreach(MultipartFileData item in provider.FileData) {  
    25.                     try {  
    26.                         string name = item.Headers.ContentDisposition.FileName.Replace("\"""");  
    27.                         string newFileName = Guid.NewGuid() + Path.GetExtension(name);  
    28.                         File.Move(item.LocalFileName, Path.Combine(rootPath, newFileName));  
    29.                         Uri baseuri = new Uri(Request.RequestUri.AbsoluteUri.Replace(Request.RequestUri.PathAndQuery, string.Empty));  
    30.                         string fileRelativePath = "~/UploadedFiles/" + newFileName;  
    31.                         Uri fileFullPath = new Uri(baseuri, VirtualPathUtility.ToAbsolute(fileRelativePath));  
    32.                         savedFilePath.Add(fileFullPath.ToString());  
    33.                     } catch (Exception ex) {  
    34.                         string message = ex.Message;  
    35.                     }  
    36.                 }  
    37.                 return Request.CreateResponse(HttpStatusCode.Created, savedFilePath);  
    38.             });  
    39.             return task;  
    40.         }  
    41.     }  
    42. }  

Add Controller to display the Index(Fileupload element)

  1. Right click on Controllers folder --> Add --> Controller --> select empty controller template -->name it.
    1. public class UploadController: Controller {  
    2.     // GET: Upload  
    3.     public ActionResult Index() {  
    4.         return View();  
    5.     }  
    6. }  
  2. Now, add the view to this action method to display UI.
  3. Replace an Index view code with the View code, given below:
    1. @{  
    2. ViewBag.Title = "www.mitechdev.com";  
    3. }  
    4. <script src="~/Scripts/jquery-1.10.2.min.js"></script>  
    5. <h2>File upload to webapi</h2>  
    6.   
    7. <div class="panel panel-info">  
    8. <div class="panel-heading">  
    File upload in Web API
    1. </div>  
    2. <div class="panel-body">  
    3.     <div class="form-group"> <input type="file" id="uploadfile" /> </div> <input id="btnSubmit" class="btn btn-default" type="button" value="Upload" />  
    4.     <div class="text-info" id="status"></div>  
    5. </div>  
    6. </div>  
    7. <script>  
    8.     $(document).ready(function() {  
    9.         $('#btnSubmit').click(function() {  
    10.             if ($('#uploadfile').val() == '') {  
    11.                 alert('Please select file');  
    12.                 return;  
    13.             }  
    14.             var formData = new FormData();  
    15.             var file = $('#uploadfile')[0];  
    16.             formData.append('file', file.files[0]);  
    17.             $.ajax({  
    18.                 url: 'http://localhost:28335/api/Uploadapi',  
    19.                 type: 'POST',  
    20.                 data: formData,  
    21.                 contentType: false,  
    22.                 processData: false,  
    23.                 success: function(d) {  
    24.                     $("#status").html("<span>File uploaded here: <a class='text-success' href=" + d + ">Open File</a></span>");  
    25.                     $('#uploadfile').val(null);  
    26.                 },  
    27.                 error: function() {  
    28.                     alert("Faild please try upload again");  
    29.                 }  
    30.             });  
    31.         });  
    32.     });  
    33. </script>  
  4. Here, I created an object to FormData() and post the file to API controller.
  5. Run the Application and see the output in the Browser.

    output

  6. After uploading the file, you can see the file by clicking on the link "Open", given below.
  7. Here, in this sample Application, I uploaded a sample TXT file. We can see this by clicking Open.

    application

Download the source code for this tutorial here