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