c# - 如何使用 HttpClient PostAsync 计算进度?

标签 c# windows-store-apps dotnet-httpclient

在我的 Windows 应用商店应用程序 (c#) 中,我需要将 MultipartFormDataContent(一些字符串内容和一些文件)上传到服务器并在响应时获得一个巨大的文件。问题 - 我不能为此使用 BackgroundDownloaders。我只能为此使用一个请求。

我使用 HttpClient.PostAsync 方法:

 using (var client = new HttpClient(httpClientHandler))
            {
                using (var content = new MultipartFormDataContent())
                {
                    content.Add(...); // prepare all strings and files content
                    try
                    {
                        using (var response = await client.PostAsync(url, content))
                        {
                            if (response.StatusCode == HttpStatusCode.OK)
                            {
                                var inputBytes = await response.Content.ReadAsByteArrayAsync();
                                // some operations with inputBytes 
                            }
                            ......
                        }
                    }
                }
            }

我的问题是:如何计算此操作的进度?

注意:我的目标是 Windows 8。而且我不能使用 Windows.Web.Http.HttpClient(支持的最低客户端 Windows 8.1)。只有 System.Net.Http.HttpClient

最佳答案

我遇到了同样的问题。我通过实现自定义 HttpContent 修复了它。我使用这个对象来跟踪上传进度的百分比,你可以添加一个事件并监听它。您应该自定义 SerializeToStreamAsync 方法。

internal class ProgressableStreamContent : HttpContent
{
    private const int defaultBufferSize = 4096;

    private Stream content;
    private int bufferSize;
    private bool contentConsumed;
    private Download downloader;

    public ProgressableStreamContent(Stream content, Download downloader) : this(content, defaultBufferSize, downloader) {}

    public ProgressableStreamContent(Stream content, int bufferSize, Download downloader)
    {
        if(content == null)
        {
            throw new ArgumentNullException("content");
        }
        if(bufferSize <= 0)
        {
            throw new ArgumentOutOfRangeException("bufferSize");
        }

        this.content = content;
        this.bufferSize = bufferSize;
        this.downloader = downloader;
    }

    protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
    {
        Contract.Assert(stream != null);

        PrepareContent();

        return Task.Run(() =>
        {
            var buffer = new Byte[this.bufferSize];
            var size = content.Length;
            var uploaded = 0;

            downloader.ChangeState(DownloadState.PendingUpload);

            using(content) while(true)
            {
                var length = content.Read(buffer, 0, buffer.Length);
                if(length <= 0) break;

                downloader.Uploaded = uploaded += length;

                stream.Write(buffer, 0, length);

                downloader.ChangeState(DownloadState.Uploading);
            }

            downloader.ChangeState(DownloadState.PendingResponse);
        });
    }

    protected override bool TryComputeLength(out long length)
    {
        length = content.Length;
        return true;
    }

    protected override void Dispose(bool disposing)
    {
        if(disposing)
        {
            content.Dispose();
        }
        base.Dispose(disposing);
    }


    private void PrepareContent()
    {
        if(contentConsumed)
        {
            // If the content needs to be written to a target stream a 2nd time, then the stream must support
            // seeking (e.g. a FileStream), otherwise the stream can't be copied a second time to a target 
            // stream (e.g. a NetworkStream).
            if(content.CanSeek)
            {
                content.Position = 0;
            }
            else
            {
                throw new InvalidOperationException("SR.net_http_content_stream_already_read");
            }
        }

        contentConsumed = true;
    }
}

仅供引用:

public interface IDownload
{
    event EventHandler<DownloadStateEventArgs> StateChanged;
    event EventHandler<DownloadStateEventArgs> Completed;

    DownloadState State { get; }
    Guid Id { get; }
    string Uri { get; }
    long Filesize { get; }
    long Downloaded { get; }

    Task DownloadAsync();
}

关于c# - 如何使用 HttpClient PostAsync 计算进度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22528839/

相关文章:

microsoft-metro - 如何在 Metro 应用程序中禁用缓存 HTTP GET,我正在使用 IXMLHTTPRequest2

windows - Windows 开始菜单中的应用程序磁贴属性

c# - HttpClient 和 ASP.NET Core 2.0 web 服务之间的连接已关闭错误

c# - 是否可以创建 DataRelation 1 :1 in c#?

c# - WPF DataTemplate 绑定(bind)取决于属性的类型

c# - 将文件复制到 metro-style-app 的安装目录

c# - Xamarin 中的 WebException,使用 HttpClient

c# - 在处置 HttpClient 之前是否需要等待异步方法完成?

javascript - 在具有有限字符的标签中显示数据

c# - 按钮触发事件不适用于边框?