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