Extracting File Bytes from Multipart/Form-Data POSTs in WCF REST Services
Web forms often use the multipart/form-data content type to post files to web services. While this allows for easy file transfers, extracting the file bytes from the multipart body can be a challenge. One solution for this problem involves leveraging the public Microsoft API introduced in .NET 4.5.
To utilize this API, you'll need to include System.Net.Http.dll and System.Net.Http.Formatting.dll in your project. If you're using .NET 4, you can obtain these assemblies through NuGet.
Once you have the assemblies in place, you can use the following code to parse the multipart body and extract the file bytes:
public static async Task ParseFiles( Stream data, string contentType, Action<string, Stream> fileProcessor) { // Create a stream content based on the input stream var streamContent = new StreamContent(data); // Set the content type header streamContent.Headers.ContentType = MediaTypeHeaderValue.Parse(contentType); // Read the multipart data as multipart content var provider = await streamContent.ReadAsMultipartAsync(); // Loop through each content retrieved from the multipart body foreach (var httpContent in provider.Contents) { // Get the file name var fileName = httpContent.Headers.ContentDisposition.FileName; // If there is a file name, ignore empty file names if (string.IsNullOrWhiteSpace(fileName)) { continue; } // Read the file content stream using (Stream fileContents = await httpContent.ReadAsStreamAsync()) { // Pass the file name and file content stream to the specified processor fileProcessor(fileName, fileContents); } } } ```` To use this code, you can create a custom file processor method, such as:
private void MyProcessMethod(string name, Stream contents)
{
// Your code to process the file data
}
The above is the detailed content of How to Extract File Bytes from Multipart/Form-Data POSTs in WCF REST Services?. For more information, please follow other related articles on the PHP Chinese website!