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>
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!