C#在WinForm下使用HttpWebRequest上传文件
时间: 2024-03-26 16:40:17 浏览: 93
在 C# WinForm 应用程序中,可以使用 HttpWebRequest 类来实现文件上传,具体步骤如下:
1. 创建 HttpWebRequest 对象,并设置请求参数。
```csharp
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uploadUrl);
request.Method = "POST";
request.ContentType = "multipart/form-data";
```
2. 构造要上传的文件数据。
```csharp
byte[] fileData = File.ReadAllBytes(filePath);
string fileName = Path.GetFileName(filePath);
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n";
string formdata = string.Format(formdataTemplate, "file", fileName);
byte[] formdataBytes = Encoding.UTF8.GetBytes(formdata);
byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
```
3. 将文件数据写入请求流中。
```csharp
Stream requestStream = request.GetRequestStream();
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
requestStream.Write(formdataBytes, 0, formdataBytes.Length);
requestStream.Write(fileData, 0, fileData.Length);
byte[] trailer = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
requestStream.Write(trailer, 0, trailer.Length);
requestStream.Close();
```
4. 发送请求并获取响应。
```csharp
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string responseString = reader.ReadToEnd();
reader.Close();
response.Close();
```
完整的代码示例如下:
```csharp
public void UploadFile(string uploadUrl, string filePath)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uploadUrl);
request.Method = "POST";
request.ContentType = "multipart/form-data";
byte[] fileData = File.ReadAllBytes(filePath);
string fileName = Path.GetFileName(filePath);
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n";
string formdata = string.Format(formdataTemplate, "file", fileName);
byte[] formdataBytes = Encoding.UTF8.GetBytes(formdata);
byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
Stream requestStream = request.GetRequestStream();
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
requestStream.Write(formdataBytes, 0, formdataBytes.Length);
requestStream.Write(fileData, 0, fileData.Length);
byte[] trailer = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
requestStream.Write(trailer, 0, trailer.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string responseString = reader.ReadToEnd();
reader.Close();
response.Close();
}
```
阅读全文