2016年5月14日 星期六

C# 採用 WebClient 上傳檔案及參數 (WebClient with Parameters) 以及進度條 Progress Bar

在C# 開發中,若希望採用http方式進行檔案傳輸,可以使用 Web Client,以下為採用 post 進行傳輸檔案且包含參數,以及讀取進度條。

WebClient uplaod file:

WebClient myWebClient = new WebClient();
NameValueCollection parameters = new NameValueCollection();
parameters.Add("FullName", _FullName);
parameters.Add("PhoneNumber", _PhoneNumber);
myWebClient.QueryString = parameters;
myWebClient.UploadProgressChanged += new UploadProgressChangedEventHandler(UploadProgressCallback);
myWebClient.UploadFileAsync(new Uri(UPLOAD_URL), FILE_PATH);

其中之 += UploadProgressChangedEvenetHandler 委派事件為:
int count = 0; //because 100 percent show two times
private 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);
    progressBar1.Value = e.ProgressPercentage;//progress bar is Windows Form Component
    if(e.ProgressPercentage == 100)
    {
        count++;
        if (count == 2 && result == DialogResult.OK) {
            MessageBox.Show("上傳已完成");
            count = 0; //after upload, want upload again, it make count back to 0.
        }
    }
}



Reference:
http://stackoverflow.com/questions/4172158/progress-bar-and-webclient
https://msdn.microsoft.com/en-us/library/36s52zhs(v=vs.110).aspx
https://msdn.microsoft.com/en-US/library/system.net.webclient.uploadprogresschanged(v=vs.110).aspx

沒有留言:

張貼留言

© Mac Taylor, 歡迎自由轉貼。
Background Email Pattern by Toby Elliott
Since 2014