Home >Backend Development >C++ >How to Send Files via HTTP POST Using C#: A Comprehensive Guide
Detailed explanation of C# HTTP POST file upload
This article will introduce in detail how to use C# to upload files to a web server. This is a common requirement in Windows application development and requires an understanding of the principles of HTTP form requests.
Implemented using HttpWebRequest (applicable before .NET 4.5)
Prior to .NET 4.5, file uploads typically used the traditional HttpWebRequest object. The steps are as follows:
req.GetRequestStream()
. Sample code:
<code class="language-csharp">HttpWebRequest req = WebRequest.Create(uri) as HttpWebRequest; req.KeepAlive = false; req.Method = "POST"; req.ContentType = file.ContentType; req.ContentLength = file.Length; using (Stream requestStream = req.GetRequestStream()) using (Stream fileStream = File.OpenRead(file.FileName)) { fileStream.CopyTo(requestStream); }</code>
Implemented using HttpClient and MultipartFormDataContent (for .NET 4.5 and above)
.NET 4.5 and later (or by using the "Microsoft.Net.Http" NuGet package in .NET 4.0), you can use HttpClient and MultipartFormDataContent to more easily simulate form requests.
Sample code:
<code class="language-csharp">private async Task<Stream> Upload(string actionUrl, string paramString, Stream paramFileStream, byte[] paramFileBytes) { HttpContent stringContent = new StringContent(paramString); HttpContent fileStreamContent = new StreamContent(paramFileStream); HttpContent bytesContent = new ByteArrayContent(paramFileBytes); using (var client = new HttpClient()) using (var formData = new MultipartFormDataContent()) { formData.Add(stringContent, "param1", "param1"); formData.Add(fileStreamContent, "file1", "file1"); formData.Add(bytesContent, "file2", "file2"); var response = await client.PostAsync(actionUrl, formData); if (response.IsSuccessStatusCode) { return await response.Content.ReadAsStreamAsync(); } } return null; }</code>
With the above steps, you can easily upload files to a web server via HTTP POST using a C# application.
The above is the detailed content of How to Send Files via HTTP POST Using C#: A Comprehensive Guide. For more information, please follow other related articles on the PHP Chinese website!