2013-03-06 112 views
0

我想使用我的Windows应用程序将多个图像文件上传到网络服务器。这里是我的代码将Windows应用程序中的文件上传到网络服务器

 public void UploadMyFile(string URL, string localFilePath) 
    { 
     HttpWebRequest req=(HttpWebRequest)WebRequest.Create(URL);      
     req.Method = "PUT"; 
     req.AllowWriteStreamBuffering = true; 

     // Retrieve request stream and wrap in StreamWriter 
     Stream reqStream = req.GetRequestStream(); 
     StreamWriter wrtr = new StreamWriter(reqStream); 

     // Open the local file 
     StreamReader rdr = new StreamReader(localFilePath); 

     // loop through the local file reading each line 
     // and writing to the request stream buffer 
     string inLine = rdr.ReadLine(); 
     while (inLine != null) 
     { 
     wrtr.WriteLine(inLine); 
     inLine = rdr.ReadLine(); 
     } 

     rdr.Close(); 
     wrtr.Close(); 

     req.GetResponse(); 
    } 

我提到以下链接 http://msdn.microsoft.com/en-us/library/aa446517.aspx

我得到异常 远程服务器返回了意外的响应:(405)不允许的方法。

+0

什么样的Web服务器端运行的应用程序? – 2013-03-06 10:19:22

+0

这是在服务器上运行的ASP.Net MVC应用程序我想在不中断Web应用程序的情况下上传文件 – NightKnight 2013-03-06 10:33:21

+0

您是否曾设法将* single *文件上传到服务器?是什么让你认为问题是客户而不是服务器? – Blachshma 2013-03-06 11:04:05

回答

1

为什么你在阅读和写作线条时,这些是图像文件?你应该读写字节块。

public void UploadMyFile(string URL, string localFilePath) 
{ 
     HttpWebRequest req=(HttpWebRequest)WebRequest.Create(URL); 

     req.Method = "PUT"; 
     req.ContentType = "application/octet-stream"; 

     using (Stream reqStream = req.GetRequestStream()) { 

      using (Stream inStream = new FileStream(localFilePath,FileMode.Open,FileAccess.Read,FileShare.Read)) { 
       inStream.CopyTo(reqStream,4096); 
      } 

      reqStream.Flush(); 
     } 

     HttpWebResponse response = (HttpWebReponse)req.GetResponse(); 
} 

您也可以尝试更简单的方式WebClient

public void UploadMyFile(string url, string localFilePath) 
{ 
    using(WebClient client = new WebClient()) { 
     client.UploadFile(url,localFilePath); 
    } 
} 
+1

我尝试了很多上传文件的方式,但没有任何工作。 – NightKnight 2013-03-06 10:32:24

相关问题