Home > Backend Development > C++ > How to Handle File Uploads via POST in ASP.NET Web API?

How to Handle File Uploads via POST in ASP.NET Web API?

Mary-Kate Olsen
Release: 2025-01-24 01:31:08
Original
667 people have browsed it

How to Handle File Uploads via POST in ASP.NET Web API?

Upload files via POST in ASP.NET Web API

File uploading in ASP.NET Web API requires a customized approach. In order to receive and process POST images or files, the current implementation must be improved.

The code snippet provided in your question ProfileImagePost attempts to receive a HttpPostedFile parameter. However, this approach may not work as expected in ASP.NET Web API.

Instead, use the following pattern to successfully handle file uploads:

<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);
    foreach (var file in provider.Contents)
    {
        var filename = file.Headers.ContentDisposition.FileName.Trim('"');
        var buffer = await file.ReadAsByteArrayAsync();
        // 使用文件名和二进制数据执行任何操作。
    }

    return Ok();
}</code>
Copy after login

This modified code snippet ensures that you can receive and handle file uploads in ASP.NET Web API by treating the incoming request as multipart data and extracting the file name and file content.

The above is the detailed content of How to Handle File Uploads via POST in ASP.NET 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