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

How to Extract File Bytes from a Multipart/Form-Data POST Stream in WCF REST?

Barbara Streisand
Release: 2025-01-01 02:45:15
Original
535 people have browsed it

How to Extract File Bytes from a Multipart/Form-Data POST Stream in WCF REST?

How to Extract File Bytes from a Multipart/Form-Data POST Stream in WCF REST

When you POST a file to a WCF REST service through a multipart/form-data request, the resulting stream contains a sequence of boundaries, headers, and file bytes. Extracting the file bytes from this stream can be challenging.

Solution: Utilizing Microsoft Public API

Microsoft provides a set of public APIs that simplify this process:

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

Implementation:

This code snippet demonstrates how to extract file bytes using these APIs:

using System.Net.Http;
using System.Net.Http.Formatting;
using System.Threading.Tasks;

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

Example Usage:

If you have a WCF REST method, you can implement it as such:

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

File Processing:

In the MyProcessMethod you can specify the actions to perform with the extracted file bytes, such as writing them to disk.

The above is the detailed content of How to Extract File Bytes from a Multipart/Form-Data POST Stream in WCF REST?. 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