Handling File Uploads in ASP.NET MVC Web API
This example demonstrates how to process file uploads using multipart/form-data in an ASP.NET MVC Web API.
The Upload
method below uses Request.Content.IsMimeMultipartContent()
to check if the request is a multipart form. If not, it throws an HttpResponseException
indicating an unsupported media type. Otherwise, it uses MultipartMemoryStreamProvider
to read the multipart data asynchronously. The code then iterates through each file, extracting the filename and content as a byte array. You can adapt the file handling logic to suit your specific needs.
<code class="language-csharp">[HttpPost("api/upload")] public async Task<IHttpActionResult> Upload() { if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } var provider = new MultipartMemoryStreamProvider(); await Request.Content.ReadAsMultipartAsync(provider); // Process uploaded files foreach (var file in provider.Contents) { var filename = file.Headers.ContentDisposition.FileName.Trim('"'); var buffer = await file.ReadAsByteArrayAsync(); // Save the file, process the data, or perform other actions here. // Example: Save to disk // var filePath = Path.Combine(Server.MapPath("~/App_Data"), filename); // File.WriteAllBytes(filePath, buffer); } return Ok(); }</code>
This improved code provides clearer comments and a more concise explanation of the process. Remember to replace the commented-out example file saving with your desired file handling logic.
The above is the detailed content of How to Accept File POST Requests in ASP.NET MVC Web API?. For more information, please follow other related articles on the PHP Chinese website!