Posting Files to Web API in Asp.Net MVC
Multipart form data Web Api
Sometimes while creating asp.net mvc project we need to send files as some other values as parameters. So for achieving that we can do following steps
So first of all we will add the code to call the api. You have to go to the controller and add following code to call api
public async Task<ActionResult> Index() { using (var httpClient = new HttpClient()) using (var formData = new MultipartFormDataContent()) { // Read the file as a byte array var filename = @"C:\Users\shubh\source\repos\RazorPay.zip"; //Change to Any file path of your system byte[] fileBytes = System.IO.File.ReadAllBytes(filename); // Create a ByteArrayContent from the file bytes var fileContent = new ByteArrayContent(fileBytes); // Add the file content to the form data formData.Add(fileContent, "file", "RazorPay.zip"); var value1 = "123"; var value2 = "Test"; var parameter1content = new StringContent(value1, Encoding.UTF8); formData.Add(parameter1content, "parameter1"); var parameter2content = new StringContent(value2, Encoding.UTF8); formData.Add(parameter2content, "parameter2"); // Add additional values as StringContent var applicationVersion = string.Empty; applicationVersion = Path.GetFileNameWithoutExtension(filename).Split('_').LastOrDefault(); HttpResponseMessage response = await httpClient.PostAsync("https://localhost:44383/api/FileUpload/Upload", formData); var responseBody = ""; // Process the response as needed if (response.IsSuccessStatusCode) { responseBody = await response.Content.ReadAsStringAsync(); // API call succeeded // Do something with the response } else { responseBody = await response.Content.ReadAsStringAsync(); // API call failed // Handle the error } } return View(); }
add following namespaces in the controller
using System.IO; using System.Linq; using System.Net.Http; using System.Text;
Now since we have added functionality to call the api , we will add new api project and will add code to create the api. So add the following code
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using System.Web.Http; namespace MultipartAPI.Controllers { public class ValuesController : ApiController { // GET api/values [HttpPost] [Route("api/FileUpload/Upload")] public async Task<IHttpActionResult> UploadReleaseFile() { if (!Request.Content.IsMimeMultipartContent()) { return BadRequest("Error : Invalid request. File is missing."); } try { // Read the multipart form data var provider = new MultipartFormDataStreamProvider(Path.GetTempPath()); await Request.Content.ReadAsMultipartAsync(provider); // Get the file data var fileData = provider.FileData.FirstOrDefault(); string filePath = provider.FileData[0].LocalFileName; string fileName = fileData.Headers.ContentDisposition.FileName.Trim('\"'); string parameter1 = provider.FormData["parameter1"]; string parameter2 = provider.FormData["parameter2"]; if (!Directory.Exists(@"F:\Upload")) //Change path as per your system { Directory.CreateDirectory(@"F:\Upload"); //Change path as per your system } // Save the file to the destination path File.Move(filePath, @"F:\Upload\" + fileName); //Change path as per your system return Ok("File Uploaded Successfully"); // Return a success response } catch (Exception ex) { return BadRequest("Error : " + ex.Message.ToString()); } } } }
Here you can see we are reading multipart data using ReadAsMultipartAsync . Then in the last we are save the file to some location. You can modify the location as per your requirement . You can also add additional parameters as per your needs. Don't forget to change the URl of the api in the first code url.
Now run the application and you will see the api posting files on the api.
If you face any trouble regarding content length than you can add following in the web.config
<system.web> <compilation debug="true" targetFramework="4.7.2" /> <httpRuntime targetFramework="4.7.2" maxRequestLength="600000000" /> </system.web> <system.webServer> <security> <requestFiltering> <requestLimits maxAllowedContentLength="600000000" /> </requestFiltering> </security> <handlers> <remove name="ExtensionlessUrlHandler-Integrated-4.0" /> <remove name="OPTIONSVerbHandler" /> <remove name="TRACEVerbHandler" /> <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /> </handlers> </system.webServer>So this is how we work with Posting Files to Web API in Asp.Net MVC.