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); } } }
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); }
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!