Home > Backend Development > C++ > How to Accept File POST Requests in ASP.NET MVC Web API?

How to Accept File POST Requests in ASP.NET MVC Web API?

Mary-Kate Olsen
Release: 2025-01-24 01:21:09
Original
1008 people have browsed it

How to Accept File POST Requests in ASP.NET MVC Web API?

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template