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.
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.
- using System;
- using System.Collections.Generic;
- using System.Collections.Specialized;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Threading.Tasks;
- using System.Web;
- using System.Web.Configuration;
- using System.Web.Http;
- using UploadDocsDummy.Models;
-
- namespace UploadDocsDummy.Controllers
- {
- public class DocumentUploadController : ApiController
- {
-
-
-
-
- [HttpPost]
- [Route("api/DocumentUpload/MediaUpload")]
- public async Task<HttpResponseMessage> MediaUpload()
- {
-
- if (!Request.Content.IsMimeMultipartContent())
- {
- throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
- }
-
- var provider = await Request.Content.ReadAsMultipartAsync<InMemoryMultipartFormDataStreamProvider>(new InMemoryMultipartFormDataStreamProvider());
-
- NameValueCollection formData = provider.FormData;
-
- IList<HttpContent> files = provider.Files;
-
- HttpContent file1 = files[0];
- var thisFileName = file1.Headers.ContentDisposition.FileName.Trim('\"');
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- string filename = String.Empty;
- Stream input = await file1.ReadAsStreamAsync();
- string directoryName = String.Empty;
- string URL = String.Empty;
- string tempDocUrl = WebConfigurationManager.AppSettings["DocsUrl"];
-
- if (formData["ClientDocs"] == "ClientDocs")
- {
- var path = HttpRuntime.AppDomainAppPath;
- directoryName = System.IO.Path.Combine(path, "ClientDocument");
- filename = System.IO.Path.Combine(directoryName, thisFileName);
-
-
- if (File.Exists(filename))
- {
- File.Delete(filename);
- }
-
- string DocsPath = tempDocUrl + "/" + "ClientDocument" + "/";
- URL = DocsPath + thisFileName;
-
- }
-
-
-
- using (Stream file = File.OpenWrite(filename))
- {
- input.CopyTo(file);
-
- file.Close();
- }
-
- var response = Request.CreateResponse(HttpStatusCode.OK);
- response.Headers.Add("DocsUrl", URL);
- return response;
- }
-
- }
- }
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.
- <appSettings>
- <add key="DocsUrl" value="http://localhost:51356" />
- </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.