在C#中實現文件上傳可以通過使用HttpWebRequest類來發送HTTP POST請求,并在請求中包含要上傳的文件。以下是一個示例代碼,演示如何使用C#實現文件上傳:
using System;
using System.IO;
using System.Net;
class Program
{
static void Main(string[] args)
{
string url = "http://example.com/upload";
string filePath = "path/to/file.txt";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
request.ContentType = "multipart/form-data; boundary=" + boundary;
using (Stream requestStream = request.GetRequestStream())
{
using (StreamWriter writer = new StreamWriter(requestStream))
{
writer.WriteLine("--" + boundary);
writer.WriteLine("Content-Disposition: form-data; name=\"file\"; filename=\"" + Path.GetFileName(filePath) + "\"");
writer.WriteLine("Content-Type: application/octet-stream");
writer.WriteLine();
using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
requestStream.Write(buffer, 0, bytesRead);
}
}
writer.WriteLine();
writer.WriteLine("--" + boundary + "--");
}
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(responseStream))
{
string responseText = reader.ReadToEnd();
Console.WriteLine(responseText);
}
}
}
}
}
在上述代碼中,首先創建一個HttpWebRequest對象,并設置請求的方法為POST。然后設置請求的Content-Type為multipart/form-data,并定義一個boundary用于分隔請求的不同部分。接著將文件內容寫入請求的流中,并在結束時添加boundary標記。最后發送請求并讀取響應內容。
請注意,以上示例中使用了HttpWebRequest類來實現文件上傳,也可以考慮使用更方便的第三方庫,如HttpClient來實現文件上傳。