假如某网站有个表单,例如(url: http://localhost/login.aspx):帐号 密码 我们需要在程序中提交数据到这个表单,对于这种表单,我们可以使用 WebClient.UploadData 方法来实现,将所要上传的数据拼成字符即可,程序很简单:string uriString = "http://localhost/login.aspx";// 创建一个新的 WebClient 实例.WebClient myWebClient = new WebClient();string postData = "Username=admin&Password=admin";// 注意这种拼字符串的ContentTypemyWebClient.Headers.Add("Content-Type","application/x-www-form-urlencoded");// 转化成二进制数组byte[] byteArray = Encoding.ASCII.GetBytes(postData);// 上传数据,并获取返回的二进制数据.byte[] responseArray = myWebClient.UploadData(uriString,"POST",byteArray);对于文件上传类的表单,例如(url: http://localhost/uploadFile.aspx):文件 对于这种表单,我们可以使用String uriString = "http://localhost/uploadFile.aspx";// 创建一个新的 WebClient 实例.WebClient myWebClient = new WebClient();string fileName = @"C:\upload.txt";// 直接上传,并获取返回的二进制数据.byte[] responseArray = myWebClient.UploadFile(uriString,"POST",fileName);还有一种表单,不仅有文字,还有文件,例如(url: http://localhost/uploadData.aspx):文件名 文件 对于这种表单,似乎前面的两种方法都不能适用,对于第一种方法,不能直接拼字符串,对于第二种,我们只能传文件,重新回到第一个方法,注意参数:public byte[] UploadData( string address, string method, byte[] data);在第一个例子中,是通过拼字符串来得到byte[] data参数值的,对于这种表单显然不行,反过来想想,对于uploadData.aspx这样的程序来说,直接通过网页提交数据,后台所获取到的流是什么样的呢?(在我以前的一篇blog中,曾分析过这个问题:asp无组件上传进度条解决方案),最终的数据如下:-----------------------------7d429871607feContent-Disposition: form-data; name="file1"; filename="G:\homepage.txt"Content-Type: text/plain宝玉:http://www.webuc.net-----------------------------7d429871607feContent-Disposition: form-data; name="filename"default filename-----------------------------7d429871607fe--所以只要拼一个这样的byte[] data数据Post过去,就可以达到同样的效果了。但是一定要注意,对于这种带有文件上传的,其ContentType是不一样的,例如上面的这种,其ContentType为"multipart/form-data; boundary=---------------------------7d429871607fe"。有了ContentType,我们就可以知道boundary(就是上面的"---------------------------7d429871607fe"),知道boundary了我们就可以构造出我们所需要的byte[] data了,最后,不要忘记,把我们构造的ContentType传到WebClient中(例如:webClient.Headers.Add("Content-Type", ContentType);)这样,就可以通过WebClient.UploadData 方法上载文件数据了。具体代码如下:生成二进制数据类的封装using System;using System.Web;using System.IO;using System.Net;using System.Text;using System.Collections;namespace UploadData.Common 相关文章: