WPF中利用WebClient向服务器上传文件

转载:原文地址http://blog.csdn.net/wj1589300/article/details/9255631

 

        WPF中利用WebClient向服务器上传文件             

忽然接到一个任务,在WPF中上传文件至服务器~在网上搜了很多种方法,最终决定利用WebCient实现文件的上传工作,看似很简单的任务,却遇到了很多问题。先说一下我的探索步骤吧~

一、选用WebClient.UploadFile方法 (String,String, String)

  1. public bool UploadFile(string newfilename)  
  2.           {  
  3.              WebClient myWebClient = new WebClient();  
  4.               myWebClient.Credentials = CredentialCache.DefaultCredentials;  
  5.               try  
  6.               {  
  7.                 //将D盘名字为hello的文档,上传到服务器中WPF的文件夹中,并以newfilename命名(newfilename含扩展名)  
  8.                   myWebClient.UploadFile(new Uri("http://localhost:9935/WPF/" + newfilename) , "PUT", @"Dhello.docx");         
  9.               }  
  10.               catch (Exception ex)  
  11.               {  
  12.                   MessageBox.Show("文件上传失败,请稍后重试!");  
  13.   
  14.               }  
  15.               return true;  
  16.           }   
public bool UploadFile(string newfilename)
          {
             WebClient myWebClient = new WebClient();
              myWebClient.Credentials = CredentialCache.DefaultCredentials;
              try
              {
                //将D盘名字为hello的文档,上传到服务器中WPF的文件夹中,并以newfilename命名(newfilename含扩展名)
                  myWebClient.UploadFile(new Uri("http://localhost:9935/WPF/" + newfilename) , "PUT", @"Dhello.docx");       
              }
              catch (Exception ex)
              {
                  MessageBox.Show("文件上传失败,请稍后重试!");

              }
              return true;
          } 

这种方法遇到了“远程服务器返回错误: (404) 未找到”问题。在网上找解决办法,把所有可能的设置都进行配置,例如(1)IIS上传目录的权限问题(加入Everyone)角色,使之可写入~(2)添加IIS的处理程序映射。首先打开IIS,左侧选择虚拟目录,右侧选择功能视图——处理程序映射——双击进入,选择ExtensionlessHandler-Integrated-4.0双击后,点击请求限制,谓词面板,下列谓词之一中添加上PUT,DELETE.但依旧走不通,奇怪的是,WebClient的下载方法以这种方式却能实现~现在依旧百思不解...

..二、WebClient UploadFile方法 (Url, String)

选用这个重载方法,第一参数是服务器上的一个网页(aspx或者ashx),第二个参数是文件在本地的地址(也是上文的"Dhello.docx")首先要在服务器端生成一个网页,该网页用来处理上传文件存放服务器请求,网页后台的具体代码如下:

  1. protected void Page_Load(object sender, EventArgs e)  
  2.         {  
  3.             foreach (string f in Request.Files.AllKeys)  
  4.             {    //在客户端传入新的文件  
  5.                 HttpPostedFile file = Request.Files[f];  
  6.                 //在客户端传入一个新的文件名               
  7.                 string filename = Request.QueryString["n"];  
  8.                 file.SaveAs(Server.MapPath("../DOC/" + filename + file.FileName.Substring(file.FileName.IndexOf("."))));  
  9.             }  
  10.         }  
  11.      
protected void Page_Load(object sender, EventArgs e)
        {
            foreach (string f in Request.Files.AllKeys)
            {    //在客户端传入新的文件
                HttpPostedFile file = Request.Files[f];
                //在客户端传入一个新的文件名             
                string filename = Request.QueryString["n"];
                file.SaveAs(Server.MapPath("../DOC/" + filename + file.FileName.Substring(file.FileName.IndexOf("."))));
            }
        }
   

在客户端需要调用WebClient的UploadFile方法,具体代码如下:

  1. public bool Upload(string filename)  
  2.        {  
  3.            WebClient myWebClient = new WebClient();  
  4.            myWebClient.Credentials = CredentialCache.DefaultCredentials; //获取或设置发送到主机并用于请求进行身份验证的网络凭据  
  5.            myWebClient.UploadFileAsync(new Uri("http://localhost:9935/WPF/UploadFile.aspx?n="+filename),@ "D:hello.docx");  
  6.            myWebClient.UploadFileCompleted += new UploadFileCompletedEventHandler(myWebClient_UploadFileCompleted);  
  7.   
  8.            return true;  
  9.        }  
  10.   
  11.        private void myWebClient_UploadFileCompleted(object sender, UploadFileCompletedEventArgs e)  
  12.        {  
  13.            if (e.Error != null)  
  14.            {  
  15.                MessageBox.Show("上传失败:" + e.Error.Message);  
  16.            }  
  17.            else {  
  18.                MessageBox.Show("上传成功!");  
  19.            }  
  20.        }  
   public bool Upload(string filename)
          {
              WebClient myWebClient = new WebClient();
              myWebClient.Credentials = CredentialCache.DefaultCredentials; //获取或设置发送到主机并用于请求进行身份验证的网络凭据
              myWebClient.UploadFileAsync(new Uri("http://localhost:9935/WPF/UploadFile.aspx?n="+filename),@ "D:hello.docx");
              myWebClient.UploadFileCompleted += new UploadFileCompletedEventHandler(myWebClient_UploadFileCompleted);

              return true;
          }

          private void myWebClient_UploadFileCompleted(object sender, UploadFileCompletedEventArgs e)
          {
              if (e.Error != null)
              {
                  MessageBox.Show("上传失败:" + e.Error.Message);
              }
              else {
                  MessageBox.Show("上传成功!");
              }
          }

在此期间也出现了一个错误,耽搁了不少时间,远程服务器返回错误:(500)内部服务器错误。这个问题出现原因一般是在服务器生成的网页中,将运行地址改为本地加断点调试,最后是存放路径出问题了,修改,运行,文件成功上传。~第一次写博客,格式没整好,还望大家多包涵~

原文地址:https://www.cnblogs.com/managersi/p/3854783.html