Skip to content

Instantly share code, notes, and snippets.

@kmonsoor
Created August 3, 2016 14:23
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kmonsoor/5ef62de8fabe0a98377e072abe6b44b4 to your computer and use it in GitHub Desktop.
Save kmonsoor/5ef62de8fabe0a98377e072abe6b44b4 to your computer and use it in GitHub Desktop.
C#.NET : WebClient : Upload file to web API while monitoring progress
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);
}
}
@ipanin
Copy link

ipanin commented Feb 6, 2021

nice

@BartSar
Copy link

BartSar commented Nov 2, 2022

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