Home > Backend Development > C++ > How to Upload Files via HTTP POST using C#?

How to Upload Files via HTTP POST using C#?

Susan Sarandon
Release: 2025-01-11 19:21:42
Original
763 people have browsed it

How to Upload Files via HTTP POST using C#?

C# HTTP POST File Upload: A Comprehensive Guide

This guide details how to use C# to upload files to a remote server via an HTTP POST request.

1. Constructing the HTTP Request

First, create an HttpWebRequest object specifying the target URL. Set the Method property to "POST", and define the ContentType and ContentLength appropriately.

2. Authentication and Connection Parameters

Configure the request's Credentials property with the necessary user credentials. Enable pre-authentication by setting PreAuthenticate to true.

3. Building Multipart Form Data

For C# 4.5 and later, leverage the MultipartFormDataContent class to create multipart form data. Add both string and file data using StringContent and StreamContent respectively.

4. Sending the Request and Handling the Response

Send the request using req.GetResponse() and manage any potential exceptions. Process the server's response accordingly.

5. Code Example

The following code demonstrates the process:

<code class="language-csharp">HttpWebRequest req = WebRequest.Create(uri) as HttpWebRequest;
req.KeepAlive = false;
req.Method = "POST";
req.Credentials = new NetworkCredential(user.UserName, user.UserPassword);
req.PreAuthenticate = true;
req.ContentType = file.ContentType;
req.ContentLength = file.Length;

using (var formData = new MultipartFormDataContent())
{
    formData.Add(new StringContent(paramString), "param1", "param1");
    formData.Add(new StreamContent(paramFileStream), "file1", "file1");
    formData.Add(new ByteArrayContent(paramFileBytes), "file2", "file2");
    using (var client = new HttpClient())
    {
        var response = await client.PostAsync(uri, formData);
        // Process the response here...
    }
}</code>
Copy after login

The above is the detailed content of How to Upload Files via HTTP POST using C#?. 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