HttpClient 上传/下载文件计算文件传输进度
1.使用ProgressMessageHandler 获取进度
using namespace System.Net.Http; HttpClientHandler hand = new HttpClientHandler(); ProgressMessageHandler processMessageHander = new ProgressMessageHandler(hand); HttpClient localHttpClient = new HttpClient(processMessageHander); processMessageHander.HttpSendProgress += (sender, e2) => { int num = e2.ProgressPercentage; //you can use HttpProgressEventArgs e worker.ReportProgress(num); };
var resp = await localHttpClient.SendAsync(httpRequestMessage);
Stream stream = await resp.Content.ReadAsStreamAsync();
2. 在已知要下载的文件大小的情况下,可以计算获取进度
var resp = await _client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead); using (Stream stream = await resp.Content.ReadAsStreamAsync(), fs = new FileStream(downloadPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite, 10240, true)) { var totalRead = 0L; var buffer = new byte[10240]; var isMoreToRead = true; do { if (worker.CancellationPending) { e.Cancel = true; return false; } var read = await stream.ReadAsync(buffer, 0, buffer.Length); if (read == 0) { isMoreToRead = false; } else { await fs.WriteAsync(buffer, 0, read); totalRead += read; int percentComplete = (int)((float)totalRead / (float)fileSize * 100); worker.ReportProgress(percentComplete); } } while (isMoreToRead); }
本文采用 知识共享署名 4.0 国际许可协议 进行许可