Created
August 3, 2016 14:23
-
-
Save kmonsoor/5ef62de8fabe0a98377e072abe6b44b4 to your computer and use it in GitHub Desktop.
C#.NET : WebClient : Upload file to web API while monitoring progress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.IO; | |
using System.Net; | |
using System.Web; | |
public class UploadWithProgress | |
{ | |
public static double PercentUploaded; | |
public static string FilePath; | |
public static string Result; | |
public static bool Completed; | |
public static string Error; | |
public static void UploadFileAsync(string api_url, string pathToFile, int userId, auth_token) | |
{ | |
FilePath = pathToFile; | |
Completed = false; | |
var uri = new Uri(api_url); | |
var client = new WebClient(); | |
// adding necessary Headers | |
client.Headers.Add("auth_token", auth_token); | |
client.QueryString.Add("userId", userId.ToString()); | |
PercentUploaded = 0.0; | |
Result = Error = null; | |
client.UploadProgressChanged += UploadProgressChanged; | |
clienta.UploadFileCompleted += UploadCompletedCallback; | |
client.UploadFileAsync(uri, "POST", pathToFile); | |
Console.WriteLine("Started uploading: " + pathToFile); | |
} | |
private static void UploadCompletedCallback(object sender, UploadFileCompletedEventArgs e) | |
{ | |
Console.WriteLine(new string('-', 12)); | |
if (e.Error != null) | |
{ | |
Error = e.Error.ToString(); | |
Console.WriteLine(Result); | |
} | |
else | |
{ | |
PercentUploaded = 100; | |
Completed = true; | |
Result = Encoding.UTF8.GetString(e.Result); | |
Console.WriteLine("File upload Completed: " + FilePath); | |
Console.WriteLine("Server Response:" + Result); | |
} | |
} | |
static void UploadProgressChanged(object sender, UploadProgressChangedEventArgs e) | |
{ | |
PercentUploaded = e.ProgressPercentage; | |
var msg = $"{e.UserState} uploaded {e.BytesSent} of {e.TotalBytesToSend} bytes. {e.ProgressPercentage} % complete..."; | |
Console.WriteLine(msg); | |
} | |
} |
Hi thanks but this does not work apparently because it needs Task
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nice