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

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

Patricia Arquette
Patricia ArquetteOriginal
2025-01-24 01:12:09800browse

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

Handling File Uploads in ASP.NET Web API

This guide demonstrates how to correctly receive POSTed files, such as images, in ASP.NET Web API. The example below avoids saving files directly to the server's file system, instead keeping the file data in memory.

Improved File Upload Method:

The following code snippet utilizes MultipartMemoryStreamProvider to efficiently handle file uploads within the Web API.

<code class="language-csharp">[HttpPost("api/upload")]
public async Task<IHttpActionResult> Upload()
{
    // Check if the request content is multipart
    if (!Request.Content.IsMimeMultipartContent())
    {
        return BadRequest("Unsupported media type.  Please use multipart/form-data.");
    }

    var provider = new MultipartMemoryStreamProvider();
    await Request.Content.ReadAsMultipartAsync(provider);

    foreach (var fileContent in provider.Contents)
    {
        // Extract filename, removing surrounding quotes
        var filename = fileContent.Headers.ContentDisposition.FileName.Trim('"');

        // Validate file type (example: only allow images)
        string[] allowedExtensions = { ".jpg", ".jpeg", ".gif", ".bmp", ".png" };
        if (!allowedExtensions.Any(ext => filename.EndsWith(ext, StringComparison.OrdinalIgnoreCase)))
        {
            return BadRequest("Invalid file type.");
        }

        // Read file data into a byte array
        var buffer = await fileContent.ReadAsByteArrayAsync();

        // Process the file data (e.g., save to database, image manipulation)
        // ... your file processing logic here ...
    }

    return Ok();
}</code>

This method checks for multipart content, extracts filenames, validates file types, reads the file data into a byte array, and then allows for custom processing of the buffer (the file's binary data). Error handling is improved by returning appropriate HTTP status codes. Remember to add necessary error handling and security measures for production environments.

The above is the detailed content of How to Properly Accept File POST Requests in ASP.NET Web API?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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