In this article, I am going to disclose how to upload multipart/form-data, picture, pdf, excel, etc. to the server using Web API. Web API is essentially used as a mediator between client and server. It exposes the server side information to the client like (Website, Android, iPhone and etc.). The client can specifically communicate with the server using Web API. Web API exposes the server information as JSON.

Here, I will explain how to make a Web API to upload images, documents, PPT, multipart/form-data, etc. on Server, and save on local folder.

What is multipart/form-data?

enctype='multipart/form-data' means that is the type of content-type for which no characters will be encoded in content. That is why this type is used while uploading the files from client to server. So multipart/form-data is used when a form requires binary data in content, like the file document, etc.
To upload multipart/form-data using Web API, follow some simple steps as given below.
Step 1 - The first step is to create a new project with MVC Web API named as "UploadDocsDummy".

In this image, you can see that I have selected both checkboxes, "MVC" and "Web API. So, you can also select both or only "Web API". Now, click "OK"



Step 2 - Create an empty folder "ClientDocument" in your application to save document/image etc.You can see in the next image which is already created.
Step 3 - Create a model class "InMemoryMultipartFormDataStreamProvider" inside Models folder and use this code. In this code, I am configuring multipart/form-data.
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.ObjectModel;
  4. using System.Collections.Specialized;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Net.Http;
  8. using System.Net.Http.Headers;
  9. using System.Threading.Tasks;
  10. using System.Web;
  11. namespace UploadDocsDummy.Models
  12. {
  13. public class InMemoryMultipartFormDataStreamProvider : MultipartStreamProvider
  14. {
  15. private NameValueCollection _formData = new NameValueCollection();
  16. private List<HttpContent> _fileContents = new List<HttpContent>();
  17. // Set of indexes of which HttpContents we designate as form data
  18. private Collection<bool> _isFormData = new Collection<bool>();
  19. /// <summary>
  20. /// Gets a <see cref="NameValueCollection"/> of form data passed as part of the multipart form data.
  21. /// </summary>
  22. public NameValueCollection FormData
  23. {
  24. get { return _formData; }
  25. }
  26. /// <summary>
  27. /// Gets list of <see cref="HttpContent"/>s which contain uploaded files as in-memory representation.
  28. /// </summary>
  29. public List<HttpContent> Files
  30. {
  31. get { return _fileContents; }
  32. }
  33. public override Stream GetStream(HttpContent parent, HttpContentHeaders headers)
  34. {
  35. // For form data, Content-Disposition header is a requirement
  36. ContentDispositionHeaderValue contentDisposition = headers.ContentDisposition;
  37. if (contentDisposition != null)
  38. {
  39. // We will post process this as form data
  40. _isFormData.Add(String.IsNullOrEmpty(contentDisposition.FileName));
  41. return new MemoryStream();
  42. }
  43. // If no Content-Disposition header was present.
  44. throw new InvalidOperationException(string.Format("Did not find required '{0}' header field in MIME multipart body part..", "Content-Disposition"));
  45. }
  46. /// <summary>
  47. /// Read the non-file contents as form data.
  48. /// </summary>
  49. /// <returns></returns>
  50. public override async Task ExecutePostProcessingAsync()
  51. {
  52. // Find instances of non-file HttpContents and read them asynchronously
  53. // to get the string content and then add that as form data
  54. for (int index = 0; index < Contents.Count; index++)
  55. {
  56. if (_isFormData[index])
  57. {
  58. HttpContent formContent = Contents[index];
  59. // Extract name from Content-Disposition header. We know from earlier that the header is present.
  60. ContentDispositionHeaderValue contentDisposition = formContent.Headers.ContentDisposition;
  61. string formFieldName = UnquoteToken(contentDisposition.Name) ?? String.Empty;
  62. // Read the contents as string data and add to form data
  63. string formFieldValue = await formContent.ReadAsStringAsync();
  64. FormData.Add(formFieldName, formFieldValue);
  65. }
  66. else
  67. {
  68. _fileContents.Add(Contents[index]);
  69. }
  70. }
  71. }
  72. /// <summary>
  73. /// Remove bounding quotes on a token if present
  74. /// </summary>
  75. /// <param name="token">Token to unquote.</param>
  76. /// <returns>Unquoted token.</returns>
  77. private static string UnquoteToken(string token)
  78. {
  79. if (String.IsNullOrWhiteSpace(token))
  80. {
  81. return token;
  82. }
  83. if (token.StartsWith("\"", StringComparison.Ordinal) && token.EndsWith("\"", StringComparison.Ordinal) && token.Length > 1)
  84. {
  85. return token.Substring(1, token.Length - 2);
  86. }
  87. return token;
  88. }
  89. }
  90. }
After that, use this class in apicontroller.
Step 4 - Create a new apiController "DocumentUploadController" inside Controllers folder.


Step 5 - If you have created a new Controller "DocumentUpload", then create a new API (Action) "MediaUpload" like this.
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.Specialized;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Net.Http;
  8. using System.Threading.Tasks;
  9. using System.Web;
  10. using System.Web.Configuration;
  11. using System.Web.Http;
  12. using UploadDocsDummy.Models;
  13. namespace UploadDocsDummy.Controllers
  14. {
  15. public class DocumentUploadController : ApiController
  16. {
  17. /// <summary>
  18. /// Upload Document.....
  19. /// </summary>
  20. /// <returns></returns>
  21. [HttpPost]
  22. [Route("api/DocumentUpload/MediaUpload")]
  23. public async Task<HttpResponseMessage> MediaUpload()
  24. {
  25. // Check if the request contains multipart/form-data.
  26. if (!Request.Content.IsMimeMultipartContent())
  27. {
  28. throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
  29. }
  30. var provider = await Request.Content.ReadAsMultipartAsync<InMemoryMultipartFormDataStreamProvider>(new InMemoryMultipartFormDataStreamProvider());
  31. //access form data
  32. NameValueCollection formData = provider.FormData;
  33. //access files
  34. IList<HttpContent> files = provider.Files;
  35. HttpContent file1 = files[0];
  36. var thisFileName = file1.Headers.ContentDisposition.FileName.Trim('\"');
  37. ////-------------------------------------For testing----------------------------------
  38. //to append any text in filename.
  39. //var thisFileName = file1.Headers.ContentDisposition.FileName.Trim('\"') + DateTime.Now.ToString("yyyyMMddHHmmssfff"); //ToDo: Uncomment this after UAT as per Jeeevan
  40. //List<string> tempFileName = thisFileName.Split('.').ToList();
  41. //int counter = 0;
  42. //foreach (var f in tempFileName)
  43. //{
  44. // if (counter == 0)
  45. // thisFileName = f;
  46. // if (counter > 0)
  47. // {
  48. // thisFileName = thisFileName + "_" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + "." + f;
  49. // }
  50. // counter++;
  51. //}
  52. ////-------------------------------------For testing----------------------------------
  53. string filename = String.Empty;
  54. Stream input = await file1.ReadAsStreamAsync();
  55. string directoryName = String.Empty;
  56. string URL = String.Empty;
  57. string tempDocUrl = WebConfigurationManager.AppSettings["DocsUrl"];
  58. if (formData["ClientDocs"] == "ClientDocs")
  59. {
  60. var path = HttpRuntime.AppDomainAppPath;
  61. directoryName = System.IO.Path.Combine(path, "ClientDocument");
  62. filename = System.IO.Path.Combine(directoryName, thisFileName);
  63. //Deletion exists file
  64. if (File.Exists(filename))
  65. {
  66. File.Delete(filename);
  67. }
  68. string DocsPath = tempDocUrl + "/" + "ClientDocument" + "/";
  69. URL = DocsPath + thisFileName;
  70. }
  71. //Directory.CreateDirectory(@directoryName);
  72. using (Stream file = File.OpenWrite(filename))
  73. {
  74. input.CopyTo(file);
  75. //close file
  76. file.Close();
  77. }
  78. var response = Request.CreateResponse(HttpStatusCode.OK);
  79. response.Headers.Add("DocsUrl", URL);
  80. return response;
  81. }
  82. }
  83. }
In this code, I have written code to save document in folder from multipart/form-data.also using "InMemoryMultipartFormDataStreamProvider"
Step 6 - Now, we need to configure "DocsUrl" in web.config file. which are using in API code to get URL. Don't forget to configure this.
  1. <appSettings>
  2. <add key="DocsUrl" value="http://localhost:51356" />
  3. </appSettings>
Now, we are ready to test API.



As shown in the above image, I have created a key in web.config file along with Models and Controllers folder.
Step 7- Run the application and use Postman to test Web API. If you are not aware about Postman, click here, otherwise see in the image how to configure Postman to test Web API.



You will put your route and use form-data and post the value and image,document.in postman. After configuring all the things click on send and see out put like this -- see image.



In this image, we are returning the file URL in header. Image has been saved in "ClientDocument" Folder.
I hope you are good to post multipart/form-data. You can download this project which I've already done.