c#HTTP POST - 需要跟踪发布/上传进度

时间:2011-08-25 20:44:12

标签: c# http post

我的代码可以很好地将文件发布到预先签名的Amazon S3网址。

但是,我想跟踪大文件的POST /上传进度。有没有一种简单的方法将其添加到我的代码中?我该怎么做?

我不需要进度条,只需要输出到控制台,文件传输的百分比就完成了,例如:

1
2
3

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);

1 个答案:

答案 0 :(得分:7)

我会使用WebClient的UploadDataAsync() method并绑定到UploadProgressChanged event

- 更新:更改样本以使用UploadDataAsync而不是UploadFileAsync

稍微修改过的样本来自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);
}