問題上傳由部分數據:如何通過HttpWebRequest的
我想通過單一的http請求上傳由塊數據和顯示每個上傳後進展的變化(物理性通過Internet發送的數據)。 (現在並不重要,我將展示上傳進度,我可以簡單地將一些數據輸出到控制檯)。
代碼:
Stackoverlow有很多這樣的問題: link 1等。(我不包括更多的鏈接,因爲我沒有足夠的聲望)。
using System;
using System.Text;
using System.IO;
using System.Net;
...
public static void UploadData()
{
const string data = "simple string";
byte[] buffer = new ASCIIEncoding().GetBytes(data);
// Thanks to http://www.posttestserver.com all is working from the box
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://posttestserver.com/post.php");
req.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.10 " +
"(KHTML, like Gecko) Chrome/8.0.552.224 Safari/534.10";
req.Accept = "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
req.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
req.Headers.Add("Accept-Language", "en-US,en;q=0.8");
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = buffer.Length;
req.SendChunked = true;
int bytesRead = buffer.Length;
const int chunkSize = 3;
Stream s = req.GetRequestStream();
for (int offset = 0; offset < bytesRead; offset += chunkSize)
{
int bytesLeft = bytesRead - offset;
int bytesWrite = bytesLeft > chunkSize ? chunkSize : bytesLeft;
s.Write(buffer, offset, bytesWrite);
}
s.Close(); // IMPORTANT: only here all data will be send
}
備註:
此外,根據 this link, 僅在每個發送過程中的每個寫入請求流必須發生,但在現實中(它可以在提琴手證明)發生的所有的發送操作在請求流關閉之後或僅通過響應獲取而不是更早。 (全部取決於SendChuncked
,AllowWriteStreamBuffering
和ContentLength
參數,但在每次寫入流後都不會發送數據)。
問題:
如何可以發送數據(物理)後,每寫(Write方法的每次調用)?
約束:
淨2.0;
僅使用HttpWebRequest原語(不是WebClient)。