Home > Backend Development > C++ > How to Upload Multipart Form Data with HttpClient in C# 4.5?

How to Upload Multipart Form Data with HttpClient in C# 4.5?

Susan Sarandon
Release: 2025-01-28 11:21:09
Original
334 people have browsed it

How to Upload Multipart Form Data with HttpClient in C# 4.5?

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template