Home > Backend Development > C++ > How Can I Extract File Bytes from a Multipart/Form-Data POST Request in .NET?

How Can I Extract File Bytes from a Multipart/Form-Data POST Request in .NET?

DDD
Release: 2025-01-04 14:24:38
Original
815 people have browsed it

How Can I Extract File Bytes from a Multipart/Form-Data POST Request in .NET?

Extracting File Bytes from Multipart/Form-Data POST

In a multipart/form-data POST, the file data is embedded within the request stream. This presents a challenge for extracting the file bytes on the server-side. One solution involves utilizing Microsoft's public APIs to parse the multipart content.

Implementation

To parse the multipart data using Microsoft's API, you will need the System.Net.Http.dll and System.Net.Http.Formatting.dll assemblies. For .NET 4.5, these assemblies are included. For .NET 4, download them via NuGet.

With the assemblies referenced, you can implement the parsing logic:

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

    var provider = await streamContent.ReadAsMultipartAsync();

    foreach (var httpContent in provider.Contents)
    {
        var fileName = httpContent.Headers.ContentDisposition.FileName;
        if (string.IsNullOrWhiteSpace(fileName))
        {
            continue;
        }

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

To use this code, you can implement a WCF REST method like the following:

[OperationContract]
[WebInvoke(Method = WebRequestMethods.Http.Post, UriTemplate = "/Upload")]
void Upload(Stream data)
{
    MultipartParser.ParseFiles(
           data, 
           WebOperationContext.Current.IncomingRequest.ContentType, 
           MyProcessMethod);
}
Copy after login

By utilizing Microsoft's APIs, you can effectively extract the file bytes from multipart/form-data POST requests, allowing you to write the files to the disk.

The above is the detailed content of How Can I Extract File Bytes from a Multipart/Form-Data POST Request in .NET?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template