2011-08-25 44 views
3

我的代碼工作正常,將文件發佈到預先簽署的Amazon S3網址。

但是,我想跟蹤POST /上傳大文件的進度。有沒有簡單的方法將其添加到我的代碼?我會怎麼做?

我並不需要一個進度條,僅僅輸出與文件傳輸的百分比控制檯完成如:
c#HTTP POST - 需要跟蹤帖子/上傳進度

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(result3) 

byte[] byteArray = 
    File.ReadAllBytes(result3); 

request.ContentLength = byteArray.Length; 

Stream dataStream = request.GetRequestStream(); 

dataStream.Write(byteArray, 0, byteArray.Length); 

dataStream.Close(); 

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

回答

7

我會用一個Web客戶端的UploadDataAsync()method,並將其綁定到其UploadProgressChangedevent

- UPDATE:改變樣品,而不是使用UploadFileAsync

UploadDataAsync

稍加修改樣本從MSDN:

public static void UploadDataInBackground (string address, byte[] data) 
    { 
     WebClient client = new WebClient(); 
     Uri uri = new Uri(address); 


     // Specify a progress notification handler. 
     client.UploadProgressChanged += new UploadProgressChangedEventHandler(UploadProgressCallback); 
     client.UploadDataAsync (uri, "POST", data); 
     Console.WriteLine ("Data upload started."); 
    } 

private static void UploadProgressCallback(object sender, UploadProgressChangedEventArgs e) 
{ 
    // Displays the operation identifier, and the transfer progress. 
    Console.WriteLine("{0} uploaded {1} of {2} bytes. {3} % complete...", 
     (string)e.UserState, 
     e.BytesSent, 
     e.TotalBytesToSend, 
     e.ProgressPercentage); 
} 
+0

我需要內容類型(.ContentType)傳遞給S3,當我使用他們的預先簽名的URL或它不會讓我發佈到S3。我可以用這個代碼來做到嗎?如果是這樣,你能修改代碼來告訴我如何? – fraXis

+0

我也需要它是同步的而不是異步的。我可以直接使用「UploadData」方法,或者如果我這樣做不會觸發事件? – fraXis

+0

我不確定。爲什麼它需要同步? – jglouie