Home >Backend Development >C++ >How to Implement a Progress Bar with HttpClient During File Downloads?

How to Implement a Progress Bar with HttpClient During File Downloads?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-12 18:46:41531browse

How to Implement a Progress Bar with HttpClient During File Downloads?

Implement progress bar when downloading files using HttpClient

Introduction

This article describes how to use HttpClient to implement a progress bar when downloading files. Since DownloadOperation cannot be used due to certificate handling limitations, another approach is required.

Use IProgress

Starting in .Net 4.5, IProgress allows asynchronous progress reporting. Here's an example of how to integrate it with HttpClient for file downloading:

// Set up HttpClient using (var client = new HttpClient()) {

<code class="language-csharp">// 带进度报告的文件下载
await client.DownloadAsync(DownloadUrl, file, progress, cancellationToken);</code>

}

Extension method implementation

The DownloadAsync extension method depends on another extension method for stream replication with progress reporting:

<code class="language-csharp">public static async Task DownloadAsync(this HttpClient client, string requestUri, Stream destination, IProgress<float> progress = null, CancellationToken cancellationToken = default) {

    // 获取内容长度的标头
    using (var response = await client.GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead)) {
        // 如果不支持,则忽略进度报告
        if (progress == null || !response.Content.Headers.ContentLength.HasValue) {
            await response.Content.ReadAsStreamAsync(cancellationToken).CopyToAsync(destination);
            return;
        }

        // 计算相对进度
        var relativeProgress = new Progress<long>(totalBytes => progress.Report((float)totalBytes / response.Content.Headers.ContentLength.Value));
        // 带进度报告的下载
        await response.Content.ReadAsStreamAsync().CopyToAsync(destination, 81920, relativeProgress, cancellationToken);
        progress.Report(1);
    }
}

public static async Task CopyToAsync(this Stream source, Stream destination, int bufferSize, IProgress<long> progress = null, CancellationToken cancellationToken = default) {

    var buffer = new byte[bufferSize];
    long totalBytesRead = 0;
    int bytesRead;
    while ((bytesRead = await source.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false)) != 0) {
        await destination.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false);
        totalBytesRead += bytesRead;
        progress?.Report(totalBytesRead);
    }
}</code>
<code>

通过以上代码,开发者可以轻松地在使用HttpClient下载文件的同时,实现进度条功能,提升用户体验。  需要注意的是,`CopyToAsync` 方法中的 `bufferSize` 参数可以根据实际情况调整,以平衡性能和内存消耗。</code>

The above is the detailed content of How to Implement a Progress Bar with HttpClient During File Downloads?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn