用WebClient.UploadData方法上載文件數(shù)據(jù)的方法
2024-07-09 22:47:04
供稿:網(wǎng)友
假如某網(wǎng)站有個(gè)表單,例如(url: http://localhost/login.aspx):
帳號(hào)
密碼
我們需要在程序中提交數(shù)據(jù)到這個(gè)表單,對(duì)于這種表單,我們可以使用 WebClient.UploadData 方法來(lái)實(shí)現(xiàn),將所要上傳的數(shù)據(jù)拼成字符即可,程序很簡(jiǎn)單:
string uriString = "http://localhost/login.aspx";
// 創(chuàng)建一個(gè)新的 WebClient 實(shí)例.
WebClient myWebClient = new WebClient();
string postData = "Username=admin&Password=admin";
// 注意這種拼字符串的ContentType
myWebClient.Headers.Add("Content-Type","application/x-www-form-urlencoded");
// 轉(zhuǎn)化成二進(jìn)制數(shù)組
byte[] byteArray = Encoding.ASCII.GetBytes(postData);
// 上傳數(shù)據(jù),并獲取返回的二進(jìn)制數(shù)據(jù).
byte[] responseArray = myWebClient.UploadData(uriString,"POST",byteArray);
對(duì)于文件上傳類的表單,例如(url: http://localhost/uploadFile.aspx):
文件
對(duì)于這種表單,我們可以使用
String uriString = "http://localhost/uploadFile.aspx";
// 創(chuàng)建一個(gè)新的 WebClient 實(shí)例.
WebClient myWebClient = new WebClient();
string fileName = @"C:upload.txt";
// 直接上傳,并獲取返回的二進(jìn)制數(shù)據(jù).
byte[] responseArray = myWebClient.UploadFile(uriString,"POST",fileName);
還有一種表單,不僅有文字,還有文件,例如(url: http://localhost/uploadData.aspx):
文件名
文件
對(duì)于這種表單,似乎前面的兩種方法都不能適用,對(duì)于第一種方法,不能直接拼字符串,對(duì)于第二種,我們只能傳文件,重新回到第一個(gè)方法,注意參數(shù):
public byte[] UploadData(
string address,
string method,
byte[] data
);
在第一個(gè)例子中,是通過拼字符串來(lái)得到byte[] data參數(shù)值的,對(duì)于這種表單顯然不行,反過來(lái)想想,對(duì)于uploadData.aspx這樣的程序來(lái)說,直接通過網(wǎng)頁(yè)提交數(shù)據(jù),后臺(tái)所獲取到的流是什么樣的呢?(在我以前的一篇blog中,曾分析過這個(gè)問題:asp無(wú)組件上傳進(jìn)度條解決方案),最終的數(shù)據(jù)如下:
-----------------------------7d429871607fe
Content-Disposition: form-data; name="file1"; filename="G:homepage.txt"
Content-Type: text/plain
寶玉:http://www.webuc.net
-----------------------------7d429871607fe
Content-Disposition: form-data; name="filename"
default filename
-----------------------------7d429871607fe--