2011-07-19 83 views
0

我已經編寫了一個支持拖放電子郵件附件和磁盤文件並將文件上傳到Web服務器的ActiveX控件。 我使用的可用的樣品在此鏈接文件上載使用HttpWebRequest的FileUpload返回(411)需要的長度錯誤

Upload files with HTTPWebrequest (multipart/form-data)

我通過設置以下屬性

  wr = (HttpWebRequest)WebRequest.Create(UploadUrl); 
      wr.ContentType = "multipart/form-data; boundary=" + boundary; 
      wr.Method = "POST"; 
      wr.ContentLength = contentLength; 
      wr.AllowWriteStreamBuffering = false; 
      wr.Timeout = 600000; 
      wr.KeepAlive = false; 
      wr.ReadWriteTimeout = 600000; 
      wr.ProtocolVersion = HttpVersion.Version10; 
      wr.Credentials = System.Net.CredentialCache.DefaultCredentials; 
      wr.SendChunked = true; 
      wr.UserAgent = "Mozilla/3.0 (compatible; My Browser/1.0)"; 
      rs = wr.GetRequestStream(); 

進行上述設定我正在一個錯誤發送以塊數據(411 )需要的長度。

在閱讀以下文章後,我意識到,當我設置SendChunked = true時,我不需要設置Content-Length屬性;

http://en.wikipedia.org/wiki/Chunked_transfer_encoding

但這裏的微軟示例代碼沒有這樣做

http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.sendchunked.aspx

進一步挖掘後,我才知道,分塊編碼僅在HTTP 1.1版本的支持。所以我改變了屬性如下 wr.ProtocolVersion = HttpVersion.Version11;

現在我再也看不到411錯誤了。

現在,能否有更好的知識驗證我在這裏的理解,請讓我知道如果我做得對。

謝謝 Ravi。

+0

「我已經寫了一個ActiveX控件」......現在有一句我沒有聽說過的短語 – heisenberg

回答

0

它們都只是讓接收者知道它何時到達傳輸結束的機制。如果你想使用Content-Length,這很簡單。只需取出您的POST數據的編碼字節數組,然後使用Length屬性。

ASCIIEncoding encoding = new ASCIIEncoding(); 
byte[] postDataByteArray = encoding.GetBytes (postData); 
wr.ContentLength = postDataByteArray.Length; 
相關問題