通过WebClient模拟post上传文件到服务器

写在前面

最近一直在研究sharepoint的文档库,在上传文件到文档库的过程中,需要模拟post请求,也查找了几种模拟方式,webclient算是比较简单的方式。

一个例子

这里写一个简单接受post请求的aspx页面,代码如下:

 1 namespace Wolfy.UploadDemo
 2 {
 3     public partial class Default : System.Web.UI.Page
 4     {
 5         protected void Page_Load(object sender, EventArgs e)
 6         {
 7             string fileName = Request.QueryString["url"];
 8             if (!string.IsNullOrEmpty(fileName))
 9             {
10                 Stream st = Request.InputStream;
11                 string fileSavePath = Request.MapPath("~/upload/") + fileName;
12                 byte[] buffer=new byte[st.Length];
13                 st.Read(buffer, 0, buffer.Length);
14                 if (!File.Exists(fileSavePath))
15                 {
16                     File.WriteAllBytes(fileSavePath, buffer);
17                 }
18                
19             }
20         }
21     }
22 }

这里使用QueryString接收url参数,使用请求的输入流接受文件的数据。
然后,使用webclient写一个模拟请求的客户端,代码如下:

 1 namespace Wolfy.UploadExe
 2 {
 3     class Program
 4     {
 5         static void Main(string[] args)
 6         {
 7             WebClient client = new WebClient();
 8             client.QueryString.Add("url", "1.png");10             using (FileStream fs = new FileStream("1.png", FileMode.Open))
11             {
12                 byte[] buffer = new byte[fs.Length];
13                 fs.Read(buffer, 0, buffer.Length);
14                 client.UploadData("http://localhost:15887/Default.aspx", buffer);
15             }
16 
17         }
18     }
19 }

调试状态运行aspx,然后运行exe控制台程序

如果有验证信息,可以加上这样一句话:

1 client.Credentials = new NetworkCredential("用户名", "密码", "");

总结

由于目前做的项目,移动端app不能提供用户名和密码,必须使用证书进行认证,发现webclient无法支持。就采用HttpWebRequest类进行模拟了。关于它的使用是下文了。

posted @ 2015-04-18 10:26  wolfy  阅读(4861)  评论(0编辑  收藏  举报