
C# HTTP POST 檔案上傳詳解
本文將詳細介紹如何使用 C# 將檔案上傳到 Web 伺服器,這在 Windows 應用程式開發中是一個常見需求,需要理解 HTTP 表單請求的原則。
使用 HttpWebRequest 實作 (適用於 .NET 4.5 之前)
在 .NET 4.5 之前,檔案上傳通常使用傳統的 HttpWebRequest 物件。步驟如下:
req.GetRequestStream() 來建立 HttpStream 物件。 範例程式碼:
<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>使用 HttpClient 和 MultipartFormDataContent 實作 (適用於 .NET 4.5 及更高版本)
.NET 4.5 及更高版本 (或透過在 .NET 4.0 中使用 "Microsoft.Net.Http" NuGet 套件),可以使用 HttpClient 和 MultipartFormDataContent 更輕鬆地模擬表單要求。
範例程式碼:
<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>透過上述步驟,您可以輕鬆地使用 C# 應用程式透過 HTTP POST 將檔案上傳到 Web 伺服器。
以上是如何使用 C# 透過 HTTP POST 傳送文件:綜合指南的詳細內容。更多資訊請關注PHP中文網其他相關文章!