Saturday, August 10, 2019

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

Steps for Web API Application(Service)

Here in this example, the Web API application (service) is "WebApiExample".

Step-1: Add a folder in the WebApi application for save 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 WebApi application

Right click on controller folder (in web api application) > Add > Controller > Enter controller name > select "Empty API Controller" from Scaffolding options > Add.

Step-3: Add a new Action into the controller (in web api application) for upload 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.  
  11. namespace WebApiExample.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. }
  55. }
  56.  

Steps for Web Application (Client Application)

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

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

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

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

Right Click on Action Method (here right click on form action) > Add View... > Enter Name > Add.
View 
  1. <h2>Part5 - Upload files to the web api using jquery</h2>
  2. <div>
  3. <div class="form-group">
  4. <div id="updatePanelFile" class="alert" role="alert" style="display:none;">
  5.  
  6. </div>
  7. </div>
  8. <div class="form-group">
  9. <input type="file" id="file1"/>
  10. </div>
  11. <input id="btnPostFile" class="btn btn-default" type="button" value="Upload" />
  12. </div>

Step-6: Add following jquery for upload file to web api

  1. <script>
  2. $(document).ready(function () {
  3. $('#btnPostFile').click(function () {
  4. if ($('#file1').val() == '') {
  5. alert('Please select file');
  6. return;
  7. }
  8.  
  9. var formData = new FormData();
  10. var file = $('#file1')[0];
  11. formData.append('file', file.files[0]);
  12. $.ajax({
  13. url: 'http://localhost:1963/api/Upload',
  14. type: 'POST',
  15. data: formData,
  16. contentType: false,
  17. processData: false,
  18. success: function (d) {
  19. $('#updatePanelFile').addClass('alert-success').html('<strong>Success!</strong><a href="' + d + '">Open File</a>').show();
  20. $('#file1').val(null);
  21. },
  22. error: function () {
  23. $('#updatePanelFile').addClass('alert-error').html('<strong>Failed!</strong> Please try again.').show();
  24. }
  25. });
  26. });
  27. });
  28. </script>
Complete View 
  1. @{
  2. ViewBag.Title = "Part5";
  3. }
  4.  
  5. <h2>Part5 - Upload files to the web api using jquery</h2>
  6. <div>
  7. <div class="form-group">
  8. <div id="updatePanelFile" class="alert" role="alert" style="display:none;">
  9.  
  10. </div>
  11. </div>
  12. <div class="form-group">
  13. <input type="file" id="file1"/>
  14. </div>
  15. <input id="btnPostFile" class="btn btn-default" type="button" value="Upload" />
  16. </div>
  17.  
  18. @section Scripts{
  19. <script>
  20. $(document).ready(function () {
  21. $('#btnPostFile').click(function () {
  22. if ($('#file1').val() == '') {
  23. alert('Please select file');
  24. return;
  25. }
  26.  
  27. var formData = new FormData();
  28. var file = $('#file1')[0];
  29. formData.append('file', file.files[0]);
  30. $.ajax({
  31. url: 'http://localhost:1963/api/Upload',
  32. type: 'POST',
  33. data: formData,
  34. contentType: false,
  35. processData: false,
  36. success: function (d) {
  37. $('#updatePanelFile').addClass('alert-success').html('<strong>Success!</strong><a href="' + d + '">Open File</a>').show();
  38. $('#file1').val(null);
  39. },
  40. error: function () {
  41. $('#updatePanelFile').addClass('alert-error').html('<strong>Failed!</strong> Please try again.').show();
  42. }
  43. });
  44. });
  45. });
  46. </script>
  47. }
  48.  
Step-7: 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 { ...