Using C# HttpClient 4.5 to Upload Multipart Form Data
The .NET 4.5 HttpClient class simplifies uploading files and structured data via a single HTTP multipart/form-data request. This guide demonstrates the process:
<code class="language-csharp">public static async Task<string> UploadFile(byte[] imageData) { using (var client = new HttpClient()) { using (var content = new MultipartFormDataContent($"Upload----{DateTime.Now.ToString(CultureInfo.InvariantCulture)}")) { content.Add(new StreamContent(new MemoryStream(imageData)), "bilddatei", "upload.jpg"); using (var response = await client.PostAsync("http://www.directupload.net/index.php?mode=upload", content)) { var responseBody = await response.Content.ReadAsStringAsync(); return !string.IsNullOrEmpty(responseBody) ? Regex.Match(responseBody, @"http://\w*\.directupload\.net/images/\d*/\w*\.[a-z]{3}").Value : null; } } } }</code>
This code snippet creates an HttpClient
and a MultipartFormDataContent
object, defining the boundary for the multipart request. The image data is added as a StreamContent
, specifying the form field name ("bilddatei") and filename ("upload.jpg").
The PostAsync
method sends the data to the specified URL. The response body is then parsed, and a regular expression extracts the uploaded file's URL. Error handling (e.g., checking response.IsSuccessStatusCode
) could be added for robustness.
The above is the detailed content of How to Upload Multipart Form Data with HttpClient in C# 4.5?. For more information, please follow other related articles on the PHP Chinese website!