HttpClient在上传之前读取整个文件。 UWP

时间:2017-03-03 22:51:19

标签: c# uwp httpclient portable-class-library dotnet-httpclient

我正在制作一个将文件上传到Facebook的UWP应用程序,我正在使用自定义HttpContent以4k块上传文件,以最大限度地减少大文件(> 100mb)的内存使用量并报告进度。

我的自定义HttpContent UploadWithProgressHttpContent:

 class UploadWithProgressHttpContent : HttpContent
{
    private readonly IProgress<OperationProgress> _progress;
    private readonly OperationProgress _data;
    private readonly Stream _file;
    private readonly int _bufferSize;
    private readonly CancellationToken _token;

    public UploadWithProgressHttpContent(
        IProgress<OperationProgress> progress,
    OperationProgress data,
    Stream file,
    int bufferSize,
    CancellationToken token)
{
    _progress = progress;
    _data = data;
    _file = file;
    _bufferSize = bufferSize;
    _token = token;
}



protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
    return CopyStreamWithProgress(_file, stream, _progress, _token, _data, _bufferSize);
}

public static async Task<Stream> CopyStreamWithProgress(
    Stream source,
    Stream destination,
    IProgress<OperationProgress> progress,
    CancellationToken token,
    OperationProgress progressData,
    int bufferSize
    )
{
    int read, offset = 0;
    var buffer = new byte[bufferSize];
    using (source)
    {
        do
        {
            read = await source.ReadAsync(buffer, 0, bufferSize, token);

            await destination.WriteAsync(buffer, 0, read, token);

            offset += read;
            progressData.CurrentSize = offset;
            progress.Report(progressData);
        } while (read != 0);
    }

    return destination;
}
}

我所遇到的(使用fiddler)是整个文件在上传开始之前被放入内存中(我的进度表在上传开始之前达到100%)。

我确实尝试将TransferEncodingChunked设置为true,然后设置文件内容长度,但问题仍然存在。

上传源位于PCL内(如果重要)。我正在使用最新版本的System.Net.Http。如果需要我使用它的方式与MediaFire SDK

中使用的方法完全相同

感谢您的帮助。

编辑:添加了HttpClient用法:

public async Task<T> Upload<T>(Stream fileStream, string fileName)
{
    var handler = new HttpClientHandler();


    var cli = new HttpClient(handler);

    foreach (var header in Headers)
    {
        cli.DefaultRequestHeaders.Add(header.Key, header.Value);
    }

    var parameters = new MultipartFormDataContent();
    foreach (var parameter in Parameters)
    {
        parameters.Add(new StringContent(parameter.Value), parameter.Key);
    }

    if (fileStream != null)
    {
        var fileContent = new UploadWithProgressHttpContent(ProgressOperation, ProgressData, fileStream,
            _chunkBufferSize, Token, fileStream.Length);

        fileContent.Headers.ContentType = new MediaTypeHeaderValue(MimeTypeHelper.GetMimeType(fileName));
        fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue(StreamParamName);
        fileContent.Headers.ContentDisposition.FileName = fileName;
        fileContent.Headers.ContentLength = fileStream.Length;
        parameters.Add(fileContent, StreamParamName);
    }

    var req = new HttpRequestMessage(method, Path) { Content = parameters };
    if (fileStream != null)
        req.Headers.TransferEncodingChunked = true;


    var completionOption = HttpCompletionOption.ResponseContentRead;


    var resp = await cli.SendAsync(req, completionOption, Token).ConfigureAwait(false);

    return await DeserializeObject<T>(resp);
}

2 个答案:

答案 0 :(得分:2)

你有与量子力学相同的问题 - 观察行为改变观察到的行为。 Fiddler不支持请求流 - 请参阅 Fiddler makes HttpWebRequest/HttpClient behaviour unexpectedhttp://www.telerik.com/forums/is-it-possible-to-not-buffer-requests

使用wireshark我可以看到这些块。

答案 1 :(得分:0)

在这个问题上浪费了几个小时后,就会发现这是一个HttpClient实现问题。 因此,如果您想要流内容到服务器(并报告进度),最好的选择是使用StreamContent并装饰读取以报告进度。

注意:这适用于System.Net.Http的4.3.1版本和版本2.2.29 Microsoft.Net.Http块包