2011-08-23 443 views
3

問題我試圖通過Amazon S3已經爲我生成的PUT請求URL發送文件到S3。C#HTTP PUT請求代碼

我的代碼適用於小文件,但在發送幾分鐘後出現大文件(> 100 MB)時出錯。

出現錯誤的是:請求被中止:請求被取消。在System.Net.ConnectStream.Write(Byte []緩衝區,Int32偏移量,Int32大小)上的System.Net.ConnectStream.InternalWrite(布爾異步,字節[]緩衝區,Int32偏移量,Int32大小,AsyncCallback回調,對象狀態)

有人可以告訴我什麼是我的代碼是阻止它發送大文件的錯誤嗎?這不是由於Amazon PUT請求URL過期導致的,因爲我已將該設置設置爲30分鐘,並且在發送幾分鐘後出現問題。

的代碼最終例外出來這行代碼:dataStream.Write(byteArray, 0, byteArray.Length);

再次,它的偉大工程,我發送給S3較小的文件。只是不大的文件。

WebRequest request = WebRequest.Create(PUT_URL_FINAL[0]); 
//PUT_URL_FINAL IS THE PRE-SIGNED AMAZON S3 URL THAT I AM SENDING THE FILE TO 

request.Timeout = 360000; //6 minutes 

request.Method = "PUT"; 

//result3 is the filename that I am sending          
request.ContentType = 
    MimeType(GlobalClass.AppDir + Path.DirectorySeparatorChar + "unzip" + 
      Path.DirectorySeparatorChar + 
      System.Web.HttpUtility.UrlEncode(result3)); 

byte[] byteArray = 
    File.ReadAllBytes(
     GlobalClass.AppDir + Path.DirectorySeparatorChar + "unzip" + 
     Path.DirectorySeparatorChar + 
     System.Web.HttpUtility.UrlEncode(result3)); 

request.ContentLength = byteArray.Length; 
Stream dataStream = request.GetRequestStream(); 

// this is the line of code that it eventually quits on. 
// Works fine for small files, not for large ones 
dataStream.Write(byteArray, 0, byteArray.Length); 

dataStream.Close(); 

//This will return "OK" if successful. 
WebResponse response = request.GetResponse(); 
Console.WriteLine("++ HttpWebResponse: " + 
        ((HttpWebResponse)response).StatusDescription); 
+0

這可能很明顯,但您確定亞馬遜的S3服務允許超過100MB的HTTP請求嗎? – Icarus

+0

我不認爲這是問題。完整的100MB永遠不會被髮送(它會在一兩分鐘後停止)。我可以使用任何第三方S3軟件程序發送文件,並通過PUT請求發送它,並且工作正常。我認爲除了S3的問題之外,我的代碼有問題。 – fraXis

+0

在上面的代碼中,您的超時時間僅爲6分鐘,而不是30分。 –

回答

2

您應該將WebRequestTimeout屬性設置爲更高的值。它會導致請求在完成之前超時。

+0

非常感謝。這是問題所在。我認爲這是一個連接超時,而不是實際的超時,超過時會阻止傳輸。 – fraXis

0

只是一個粗略的猜測,但你不應該有:

request.ContentLength = byteArray.LongLength; 

代替:

request.ContentLength = byteArray.Length; 

有第二個想法,100 MB = 100 * 1024 * 1024 < 2^32,所以它可能不會是問題

+0

這沒有任何影響。不管怎麼說,多謝拉。 – fraXis

2

使用FiddlerWireshark比較線纜工作時(第三方工具)和不工作時的情況(您的代碼)...一旦您知道差異,您可以相應地更改您的代碼...

1

I會嘗試將它寫入塊並分割字節數組。它可能會窒息在一個大塊。

事情是這樣的:

 const int chunkSize = 500; 
     for (int i = 0; i < byteArray.Length; i += chunkSize) 
     { 
      int count = i + chunkSize > byteArray.Length ? byteArray.Length - i : chunkSize; 
      dataStream.Write(byteArray, i, count); 
     } 

可能要仔細檢查,以確保它寫的一切,我只是做了很基本的測試。

+0

你能告訴我我該怎麼做? – fraXis

+0

@fraXis完成。將塊大小更改爲任何您認爲合適的值,可能是8KB或更多,500字節只是一個示例。 – Davy8