fraXis
fraXis

Reputation: 3221

c# HTTP POST -- need to track post/upload progress

My code works fine to POST a file to a pre-signed Amazon S3 url.

However, I want to track the progress of the POST/upload for large files. Is there an easy way to add this to my code? How would I do that?

I don't need a progress bar, just an output to the console with the percentage of the file transfer that is complete such as:

1
2
3
etc

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

Upvotes: 3

Views: 5229

Answers (1)

jglouie
jglouie

Reputation: 12880

I would use a WebClient's UploadDataAsync() method and tie into its UploadProgressChanged event.

-- UPDATE: changed sample to use UploadDataAsync instead of UploadFileAsync

Slightly modified sample From the 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);
}

Upvotes: 7

Related Questions