ASP.NET Web API Using MVC And jQuery To Upload And Download Files - Part Seven

Introduction
 
Web API is the best fit to create a resource-oriented service using HTTP/Restful and it works well with MVC-based applications. For more details, visit this link.
Description

In this session, I will show you how to insert records using AP.NET Web API using HttpClient to post the data in SQL Server. In this session, you can see get and post operations by Web API. In another way, I can say we'll insert and retrieve records using button click event.

Before going through this session, visit my previous sessions:
 
 
Steps to be followed.
 
Step 1
 
Add a folder in the Web API application for saving the uploaded files. Go to Solution Explorer > Right-click on Project Name (Web API) > Add > New Folder > Rename folder (here I renamed "uploadFiles").
 
Step 2
 
Add a new controller in our Web API application. Right-click on controller folder (in Web API application) > Add > Controller > Enter controller name(UploadController) > select "Empty API Controller" from Scaffolding options > Add.
 
Code Ref
  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.   
  11. namespace SatyaWebApi.Controllers  
  12. {  
  13.     public class UploadController : ApiController  
  14.     {  
  15.         public Task<HttpResponseMessage> Post()  
  16.         {  
  17.             List<string> savedFilePath = new List<string>();  
  18.             if (!Request.Content.IsMimeMultipartContent())  
  19.             {  
  20.                 throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);  
  21.             }  
  22.             string rootPath = HttpContext.Current.Server.MapPath("~/uploadFiles");  
  23.             var provider = new MultipartFileStreamProvider(rootPath);  
  24.             var task = Request.Content.ReadAsMultipartAsync(provider).  
  25.                 ContinueWith<HttpResponseMessage>(t =>  
  26.                 {  
  27.                     if (t.IsCanceled || t.IsFaulted)  
  28.                     {  
  29.                         Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);  
  30.                     }  
  31.                     foreach (MultipartFileData item in provider.FileData)  
  32.                     {  
  33.                         try  
  34.                         {  
  35.                             string name = item.Headers.ContentDisposition.FileName.Replace("\"""");  
  36.                             string newFileName = Guid.NewGuid() + Path.GetExtension(name);  
  37.                             File.Move(item.LocalFileName, Path.Combine(rootPath, newFileName));  
  38.   
  39.                             Uri baseuri = new Uri(Request.RequestUri.AbsoluteUri.Replace(Request.RequestUri.PathAndQuery, string.Empty));  
  40.                             string fileRelativePath = "~/uploadFiles/" + newFileName;  
  41.                             Uri fileFullPath = new Uri(baseuri, VirtualPathUtility.ToAbsolute(fileRelativePath));  
  42.                             savedFilePath.Add(fileFullPath.ToString());  
  43.                         }  
  44.                         catch (Exception ex)  
  45.                         {  
  46.                             string message = ex.Message;  
  47.                         }  
  48.                     }  
  49.   
  50.                     return Request.CreateResponse(HttpStatusCode.Created, savedFilePath);  
  51.                 });  
  52.             return task;  
  53.         }  
  54.     }  

Code Description
 
Added a new Action into the controller (in Web API application) for uploading the file. I have mentioned the upload file path as mentioned below.
  1. string rootPath = HttpContext.Current.Server.MapPath("~/uploadFiles"); 
After successful upload, then download the file using code as mentioned below.
  1. try  
  2.                         {  
  3.                             string name = item.Headers.ContentDisposition.FileName.Replace("\"""");  
  4.                             string newFileName = Guid.NewGuid() + Path.GetExtension(name);  
  5.                             File.Move(item.LocalFileName, Path.Combine(rootPath, newFileName));  
  6.   
  7.                             Uri baseuri = new Uri(Request.RequestUri.AbsoluteUri.Replace(Request.RequestUri.PathAndQuery, string.Empty));  
  8.                             string fileRelativePath = "~/uploadFiles/" + newFileName;  
  9.                             Uri fileFullPath = new Uri(baseuri, VirtualPathUtility.ToAbsolute(fileRelativePath));  
  10.                             savedFilePath.Add(fileFullPath.ToString());  
  11.                         } 
Two important classes are used as mentioned below.
  1. MultipartFileStreamProvider Class
    Suited for writing each MIME body parts of the MIME multipart message to a file using a FileStream.

  2. MultipartFileData Class
    Represents a multipart file data.

Upload multiple files using MultipartFormDataStreamProvider in ASP.NET WebAPI. The concept is based on Multipart/form-data in which we can POST not only multiple file content but also regular form fields which will be available as NameValueCollection on the server side.

In this tutorial, we also see how to override the default behavior of MultipartFormDataStreamProvider which stores the name in a unique BodyPart_{GUID} format to a much more meaningful name. We will also invoke our Web API using Fiddler to POST file data. Alongside, we develop a sample console application which will POST file data using HttpClient class.

Step 3
 
Add an Action to the HomeController (in MVC Client application) for getting the view of the uploaded file.
 
Code Ref
  1. public ActionResult Part5()  
  2.         {  
  3.             return View();  
  4.         } 
Step 4
 
Add View for the Action & Design. Right-click on action method (here, right-click on form action) > Add View... > Enter Name > Add.
 
Code Ref
  1. @{  
  2.     ViewBag.Title = "Part5";  
  3. }  
  4.   
  5. <style>  
  6.     table {  
  7.         font-family: arial, sans-serif;  
  8.         border-collapse: collapse;  
  9.         width: 100%;  
  10.     }  
  11.   
  12.     td, th {  
  13.         border: 1px solid #dddddd;  
  14.         text-align: left;  
  15.         padding: 8px;  
  16.     }  
  17.   
  18.     tr:nth-child(even) {  
  19.         background-color: #dddddd;  
  20.     }  
  21.   
  22.     .button {  
  23.         background-color: #4CAF50;  
  24.         border: none;  
  25.         color: white;  
  26.         padding: 15px 32px;  
  27.         text-align: center;  
  28.         text-decoration: none;  
  29.         display: inline-block;  
  30.         font-size: 16px;  
  31.         margin: 4px 2px;  
  32.         cursor: pointer;  
  33.     }  
  34.   
  35.     .button4 {  
  36.         border-radius: 9px;  
  37.     }  
  38. </style>  
  39.   
  40. <fieldset>  
  41.   
  42.     <legend style="font-family:Arial Black;color:blue">Upload And Download Files Here</legend>  
  43.   
  44.     <div>  
  45.         <div class="form-group">  
  46.             <div id="updatePanelFile" class="alert" role="alert" style="display:none;">  
  47.   
  48.             </div>  
  49.         </div>  
  50.         <div class="col-md-12" style="text-align:center;margin-bottom:10px;">  
  51.             <input type="file" id="file1" class="btn btn-primary" />  
  52.         </div>  
  53.         <input id="btnPostFile" class="button button4" type="button" value="Upload" />  
  54.     </div>  
  55.   
  56.     @section Scripts{  
  57.         <script>  
  58.             $(document).ready(function () {  
  59.                 $('#btnPostFile').click(function () {  
  60.                     if ($('#file1').val() == '') {  
  61.                         alert('Please select file');  
  62.                         return;  
  63.                     }  
  64.   
  65.                     var formData = new FormData();  
  66.                     var file = $('#file1')[0];  
  67.                     formData.append('file', file.files[0]);  
  68.                     $.ajax({  
  69.                         url: 'http://localhost:47250/api/Upload',  
  70.                         type: 'POST',  
  71.                         data: formData,  
  72.                         contentType: false,  
  73.                         processData: false,  
  74.                         success: function (d) {  
  75.                             $('#updatePanelFile').addClass('alert-success').html('<strong>Upload Done!</strong><a href="' + d + '">Download File</a>').show();  
  76.                             $('#file1').val(null);  
  77.                         },  
  78.                         error: function () {  
  79.                             $('#updatePanelFile').addClass('alert-error').html('<strong>Failed!</strong> Please try again.').show();  
  80.                         }  
  81.                     });  
  82.                 });  
  83.             });  
  84.         </script>  
  85.     }  
  86.     </fieldset> 
Code Description
 
Add the following jQuery using Web API URL for uploading the file to Web API.
  1. $.ajax({  
  2.                         url: 'http://localhost:47250/api/Upload',  
  3.                         type: 'POST',  
  4.                         data: formData,  
  5.                         contentType: false,  
  6.                         processData: false,  
  7.                         success: function (d) {  
  8.                             $('#updatePanelFile').addClass('alert-success').html('<strong>Upload Done!</strong><a href="' + d + '">Download File</a>').show();  
  9.                             $('#file1').val(null);  
  10.                         } 
After file is uploaded successfully, the file link will be available to download using panel.
  1. success: function (d) {  
  2.                             $('#updatePanelFile').addClass('alert-success').html('<strong>Upload Done!</strong><a href="' + d + '">Download File</a>').show();  
  3.                             $('#file1').val(null);  
  4.                         } 
If we face any problem in Web API URL or server issue, then we'll get a warning message as mentioned below.
  1. error: function () {  
  2.                             $('#updatePanelFile').addClass('alert-error').html('<strong>Failed!</strong> Please try again.').show();  
  3.                         } 
OUTPUT
 
Upload the file here.
 
 
Below, the panel is showing download file option after successfully uploading in Web API.
 
 
This is the path of Web API where files are uploaded with a different name.
 
 
Check all uploaded files in Web API URL path.
 
 
 
 
Summary
  • Upload files using Web API and Download files from it.
  • Implementation of MultipartFileStreamProvider Class.
  • Implementation of MultipartFileData Class.


Similar Articles