Saturday, August 10, 2019

How to upload files in the ASP.NET Web API using Http Client

Steps for Web Application (Client Application)

Here in this example, the client application is "WebApiClient.Web".

Step-1: Add an Action to the HomeController (in MVC Client application) for get view for upload file.

  1. public ActionResult Part6()
  2. {
  3. return View();
  4. }

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

Right Click on Action Method (here right click on form action) > Add View... > Enter Name > Add.
View 
  1. @{
  2. ViewBag.Title = "Part6";
  3. }
  4.  
  5. <h2>Part6 - Upload file to web api using Http Client</h2>
  6. <div class="container">
  7. <div>
  8. @if (ViewBag.Success != null)
  9. {
  10. <div class="alert alert-success" role="alert">
  11. <strong>Well done !</strong> Successfully uploaded. <a href="@ViewBag.Success" target="_blank">open file</a>
  12. </div>
  13. }
  14. else if(ViewBag.Failed != null)
  15. {
  16. <div class="alert alert-error" role="alert">
  17. <strong>Error !</strong> @ViewBag.Failed
  18. </div>
  19. }
  20. </div>
  21. @using (Html.BeginForm("Part6","Home", FormMethod.Post,new{ role = "form", enctype="multipart/form-data"}))
  22. {
  23. <div class="form-group">
  24. <input type="file" id="file" name="file" />
  25. </div>
  26. <input type="submit" value="Submit" class="btn btn-default" />
  27. }
  28. </div>

Step-3: Add an another action for POST action for upload file to web api using HttpClient

  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:1963/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. }

Step-4: Run Application.

Here we need to start both application as the client application will consume services from web api application.

No comments:

Post a Comment

How to register multiple implementations of the same interface in Asp.Net Core?

 Problem: I have services that are derived from the same interface. public interface IService { } public class ServiceA : IService { ...