[英]How can I calculate progress with HttpClient PostAsync?
在我的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();
}
WebAPI Client nuget有一些用於執行此操作的類。 看一下ProgressMessageHandler 。 它是一個PCL庫,所以它應該適用於Windows應用商店應用程序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.