How do I use HttpClient (C#) to send a multipart/form-data request?

To send a multipart/form-data request using HttpClient in C#, you need to use the MultipartFormDataContent class, which allows you to construct the multipart content by adding HttpContent instances for each part of the form data. Below is a step-by-step example that demonstrates how to send a multipart/form-data request, including text fields and a file upload.

Step 1: Set up the HttpClient

First, you need to initialize HttpClient. It's recommended to use HttpClient as a singleton or static instance rather than creating a new instance for each request to avoid socket exhaustion.

using System.Net.Http;

// ...

// HttpClient should be instantiated once and reused throughout the life of an application.
// The following code assumes a static or singleton HttpClient instance.
private static readonly HttpClient client = new HttpClient();

Step 2: Create the MultipartFormDataContent

Create an instance of MultipartFormDataContent and add the parts you need to send. For text fields use StringContent, and for file uploads use ByteArrayContent or StreamContent.

using System.Net.Http;
using System.IO;
using System.Text;

// ...

var multipartContent = new MultipartFormDataContent();

// Add string fields
multipartContent.Add(new StringContent("your value here"), "field1");
multipartContent.Add(new StringContent("another value"), "field2");

// Add a file
var filePath = @"path\to\your\file.jpg";
var fileStream = new FileStream(filePath, FileMode.Open);
var streamContent = new StreamContent(fileStream);
streamContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/jpeg");

multipartContent.Add(streamContent, "file", Path.GetFileName(filePath));

Step 3: Send the Request

Use the HttpClient.PostAsync method to send the multipart request to the server.

// ...

var requestUri = "http://example.com/api/upload";
HttpResponseMessage response = await client.PostAsync(requestUri, multipartContent);

// Ensure the request was a success
if (response.IsSuccessStatusCode)
{
    string responseContent = await response.Content.ReadAsStringAsync();
    Console.WriteLine(responseContent);
}
else
{
    // Handle the error
    Console.WriteLine($"Error: {response.StatusCode}");
}

// Dispose of the file stream and multipart content
fileStream.Dispose();
multipartContent.Dispose();

Full Example

Here's a full example that combines all of the steps:

using System;
using System.Net.Http;
using System.IO;
using System.Threading.Tasks;

class Program
{
    private static readonly HttpClient client = new HttpClient();

    static async Task Main(string[] args)
    {
        var multipartContent = new MultipartFormDataContent();

        // Add string fields
        multipartContent.Add(new StringContent("your value here"), "field1");
        multipartContent.Add(new StringContent("another value"), "field2");

        // Add a file
        var filePath = @"path\to\your\file.jpg";
        var fileStream = new FileStream(filePath, FileMode.Open);
        var streamContent = new StreamContent(fileStream);
        streamContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/jpeg");

        multipartContent.Add(streamContent, "file", Path.GetFileName(filePath));

        var requestUri = "http://example.com/api/upload";
        HttpResponseMessage response = await client.PostAsync(requestUri, multipartContent);

        // Ensure the request was a success
        if (response.IsSuccessStatusCode)
        {
            string responseContent = await response.Content.ReadAsStringAsync();
            Console.WriteLine(responseContent);
        }
        else
        {
            // Handle the error
            Console.WriteLine($"Error: {response.StatusCode}");
        }

        // Dispose of the file stream and multipart content
        fileStream.Dispose();
        multipartContent.Dispose();
    }
}

Remember to replace "http://example.com/api/upload" with the actual URI you are posting to, and provide the actual path and name of the file you want to upload. If you're uploading multiple files, you can add multiple file parts to the MultipartFormDataContent. Always ensure you dispose of StreamContent and MultipartFormDataContent to release resources once the upload is complete.

Additionally, you may need to handle exceptions and add authentication headers depending on the API you're working with.

Related Questions

Get Started Now

WebScraping.AI provides rotating proxies, Chromium rendering and built-in HTML parser for web scraping
Icon