Home > Backend Development > C++ > How to Efficiently Extract File Bytes from a Multipart/Form-Data POST Request Stream?

How to Efficiently Extract File Bytes from a Multipart/Form-Data POST Request Stream?

Mary-Kate Olsen
Release: 2025-01-01 01:23:08
Original
211 people have browsed it

How to Efficiently Extract File Bytes from a Multipart/Form-Data POST Request Stream?

Multipart/Form-Data POST and File Input Streaming

Question:

When posting a file to a REST service using multipart/form-data, how can the file bytes be efficiently extracted from the request stream for processing?

Answer:

To extract file bytes from a multipart/form-data POST request stream, a comprehensive approach using Microsoft public APIs is available.

Prerequisites:

  • System.Net.Http.dll (included in .NET 4.5 or via NuGet for .NET 4)
  • System.Net.Http.Formatting.dll (via NuGet for .NET 4.5 or .NET 4)

Code Implementation:

public static async Task ParseFiles(
    Stream data, string contentType, Action<string, Stream> fileProcessor)
{
    // Parse multipart request content
    var streamContent = new StreamContent(data);
    streamContent.Headers.ContentType = MediaTypeHeaderValue.Parse(contentType);
    var provider = await streamContent.ReadAsMultipartAsync();

    // Iterate through file parts
    foreach (var httpContent in provider.Contents)
    {
        var fileName = httpContent.Headers.ContentDisposition.FileName;
        if (string.IsNullOrWhiteSpace(fileName)) continue;

        using (Stream fileContents = await httpContent.ReadAsStreamAsync())
        {
            // Process file bytes
            fileProcessor(fileName, fileContents);
        }
    }
}
Copy after login

Sample Usage:

For a WCF REST method "OperationContract", you can implement the file processing:

public void Upload(Stream data)
{
    MultipartParser.ParseFiles(
           data, 
           WebOperationContext.Current.IncomingRequest.ContentType, 
           MyProcessMethod);
}
Copy after login

By utilizing this approach, developers can effortlessly retrieve file bytes from multipart/form-data POST requests for subsequent processing and storage.

The above is the detailed content of How to Efficiently Extract File Bytes from a Multipart/Form-Data POST Request Stream?. For more information, please follow other related articles on the PHP Chinese website!

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