且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-08-27 15:35:12

写在前面

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

一个例子

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

通过WebClient模拟post上传文件到服务器
 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 }
通过WebClient模拟post上传文件到服务器

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

通过WebClient模拟post上传文件到服务器
 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 }
通过WebClient模拟post上传文件到服务器

调试状态运行aspx,然后运行exe控制台程序
通过WebClient模拟post上传文件到服务器

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

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

总结

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

博客地址: http://www.cnblogs.com/wolf-sun/
博客版权: 本文以学习、研究和分享为主,欢迎转载,但必须在文章页面明显位置给出原文连接。
如果文中有不妥或者错误的地方还望高手的你指出,以免误人子弟。如果觉得本文对你有所帮助不如【推荐】一下!如果你有更好的建议,不如留言一起讨论,共同进步!
再次感谢您耐心的读完本篇文章。http://www.cnblogs.com/wolf-sun/p/4436930.html