文件上传使用Webclient.Uploadfile中获取上传进度
问题描述:
我有一个应用程序使用Web客户端的文件上传到服务器。 我想显示一个进度条,而在文件上传过程中。 我将如何实现这一目标?
I have an app that uploads files to server using the webclient. I'd like to display a progressbar while the file upload is in progress. How would I go about achieving this?
答
WebClient.UploadFileAsync 可以让你做到这一点。
WebClient.UploadFileAsync will allow you to do this.
WebClient webClient = new WebClient();
webClient.UploadFileAsync(address, fileName);
webClient.UploadProgressChanged += WebClientUploadProgressChanged;
...
void WebClientUploadProgressChanged(object sender, UploadProgressChangedEventArgs e)
{
Console.WriteLine("Download {0}% complete. ", e.ProgressPercentage);
}
请注意,该线程不会对上传挡住了,所以我建议使用:
Note that the thread won't block on Upload anymore, so I'd recommend using:
webClient.UploadFileCompleted += WebClientUploadCompleted;
...
void WebClientUploadCompleted(object sender, UploadFileCompletedEventArgs e)
{
// The upload is finished, clean up
}