ASP.NET Web API Using MVC And HttpClient To Upload And Download Files - Part Eight

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 the steps to upload files in the ASP.NET Web API using HttpClient and Download files from the folder in ASP.NET Web API.
 
Before going through this session, visit my previous sessions,
Steps to be followed.
 
Step 1
 
Add an Action to the HomeController (in MVC Client application) for getting the View for upload file.
 
Code Ref
  1. public ActionResult Part6()  
  2.       {  
  3.           return View();  
  4.       } 
Step 2
 
Add another action for POST action for upload file to web API using HttpClient.
 
Code Ref
  1. [HttpPost]  
  2.         public ActionResult Part6(HttpPostedFileBase file)  
  3.         {  
  4.             using (var client = new HttpClient())  
  5.             {  
  6.                 using (var content = new MultipartFormDataContent())  
  7.                 {  
  8.                     byte[] Bytes = new byte[file.InputStream.Length + 1];  
  9.                     file.InputStream.Read(Bytes, 0, Bytes.Length);  
  10.                     var fileContent = new ByteArrayContent(Bytes);  
  11.                     fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = file.FileName };  
  12.                     content.Add(fileContent);  
  13.                     var requestUri = "http://localhost:47250/api/Upload";  
  14.                     var result = client.PostAsync(requestUri, content).Result;  
  15.                     if (result.StatusCode == System.Net.HttpStatusCode.Created)  
  16.                     {  
  17.                         List<string> m = result.Content.ReadAsAsync<List<string>>().Result;  
  18.                         ViewBag.Success = m.FirstOrDefault();  
  19.   
  20.                     }  
  21.                     else  
  22.                     {  
  23.                         ViewBag.Failed = "Failed !" + result.Content.ToString();  
  24.                     }  
  25.                 }  
  26.             }  
  27.             return View();  
  28.         } 
Code Description
 
In this section, I have added Web API Url to upload files and download files from it.
  1. var requestUri = "http://localhost:47250/api/Upload"

When developing an ASP.NET Web API controller method that allows downloading a file, it is considered a good practice to set a "Content-Disposition" header to guide a browser of a name of a file being downloaded.

There are two different ways to approach this simple task. First is to add a new HTTP header to the HTTP response using string values for the header's name and value. The second is to try and use the .NET Framework's infrastructure methods that presumably should make this task easier.

The first method seems to be very simple but potentially dangerous: one would need to hard-code string values and be totally responsible for the values to be properly formatted according to the W3C standards.
  1. var fileContent = new ByteArrayContent(Bytes);  
  2. fileContent.Headers.Add("Content-Disposition""attachment; filename=fileName.ext"); 
The second method is to try and delegate handling of the specifics of the HTTP protocol to the .NET Framework by using corresponding presumably built-in methods. This seems more appropriate and even easier to achieve. However, due to poor documentation of the Web API extensions that is easier said than done. Without further ado this is how it's done:
  1. var fileContent = new ByteArrayContent(Bytes);  
  2.                     fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = file.FileName };  
  3.                     content.Add(fileContent); 
Then if the file in Asp.Net Web API is  uploaded successfully then the success message will be shown otherwise a failed message is sent to the end user.
  1. var requestUri = "http://localhost:47250/api/Upload";  
  2.                     var result = client.PostAsync(requestUri, content).Result;  
  3.                     if (result.StatusCode == System.Net.HttpStatusCode.Created)  
  4.                     {  
  5.                         List<string> m = result.Content.ReadAsAsync<List<string>>().Result;  
  6.                         ViewBag.Success = m.FirstOrDefault();  
  7.   
  8.                     }  
  9.                     else  
  10.                     {  
  11.                         ViewBag.Failed = "Failed !" + result.Content.ToString();  
  12.                     } 
Step 3
 
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 = "Part6";  
  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 class="container">  
  45.         <div>  
  46.             @if (ViewBag.Success != null)  
  47.             {  
  48.                 <div class="alert alert-success" role="alert">  
  49.                     <strong>Well done !</strong> Successfully uploaded. <a href="@ViewBag.Success" target="_blank">Download File</a>  
  50.                 </div>  
  51.             }  
  52.             else if (ViewBag.Failed != null)  
  53.             {  
  54.                 <div class="alert alert-error" role="alert">  
  55.                     <strong>Error !</strong> @ViewBag.Failed  
  56.                 </div>  
  57.             }  
  58.         </div>  
  59.         @using (Html.BeginForm("Part6""Home", FormMethod.Post, new { role = "form", enctype = "multipart/form-data" }))  
  60.         {  
  61.             <div class="form-group">  
  62.                 <input type="file" id="file" name="file" class="btn btn-primary" />  
  63.             </div>  
  64.             <input type="submit" value="Submit" class="button button4" />  
  65.         }  
  66.     </div>  
  67. </fieldset> 
Code Description
 
Here in form post method I have added controls as shown beow.
  1. @using (Html.BeginForm("Part6""Home", FormMethod.Post, new { role = "form", enctype = "multipart/form-data" }))  
  2.        {  
  3.            <div class="form-group">  
  4.                <input type="file" id="file" name="file" class="btn btn-primary" />  
  5.            </div>  
  6.            <input type="submit" value="Submit" class="button button4" />  
  7.        } 
In controller section it will check if  file has uploaded; if yes then the success message using viewbag is mentioned here.
  1. @if (ViewBag.Success != null)  
  2.             {  
  3.                 <div class="alert alert-success" role="alert">  
  4.                     <strong>Well done !</strong> Successfully uploaded. <a href="@ViewBag.Success" target="_blank">Download File</a>  
  5.                 </div>  
  6.             } 
In controller section it will check if file has uploaded; if no then the failed message using viewbag is mentioned here. 
  1. else if (ViewBag.Failed != null)  
  2.             {  
  3.                 <div class="alert alert-error" role="alert">  
  4.                     <strong>Error !</strong> @ViewBag.Failed  
  5.                 </div>  
  6.             }  
OUTPUT
 
File upload page is shown like this.
 
 
Download link file after successful upload in Asp.Net Web API.
 
 
After file download it is shown like this.
 
SUMMARY
  • Upload files using HttpClient In Web API and Download files from it.
  • Implementation of ContentDispositionHeaderValue Class.

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now