2013-03-06 109 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

相關問題