简体   繁体   English

在.net Core中使用HttpClient下载分块编码的文件

[英]Download chunked encoded file using HttpClient in .net Core

I'm using an API to download a file using HttpClient. 我正在使用API​​使用HttpClient下载文件。 When my entire file fits in a single request, I'm able to save the file and open it correctly. 当我的整个文件适合一个请求时,我可以保存文件并正确打开它。

When the entire file does not fit in my maximum chunk size, I have to do multiple requests to my API to get the file and it's returned chunked encoded. 当整个文件不适合我的最大块大小时,我必须对我的API进行多个请求才能获取该文件,然后以块编码形式返回该文件。 By guess is that the chunks are not decoded properly and end up in my file which corrupts it. 据推测,这些块未正确解码,并最终损坏了我的文件。

Is there a way to chunk decode the response from GetStreamAsync? 有没有一种方法可以对来自GetStreamAsync的响应进行分块解码?

public byte[] GetFileContent(File file)
{
    var baseFileUri = BASE_URI + $"platform/files/{file.Id}";

    int chunkSize = 128 * 1024;

    chunkSize = file.NativeSize <= chunkSize ? file.NativeSize : chunkSize;
    int start = 0;

    using (MemoryStream stream = new MemoryStream())
    {
        while (start < file.NativeSize)
        {
            Get(baseFileUri, new List<KeyValuePair<string, string>>() { new KeyValuePair<string, string>("offset", start.ToString()), new KeyValuePair<string, string>("size", chunkSize.ToString()) }, stream);

            start = start + chunkSize;

            if (file.NativeSize < start + chunkSize)
            {
                chunkSize = file.NativeSize - start;
            }
        }

        return stream.ToArray();
    }
}

private void Get(string uri, List<KeyValuePair<string, string>> parameters, Stream stream)
{
    var requestUri = BuildUriString(uri, parameters);

    var methodResult = _client.GetStreamAsync(requestUri);
    methodResult.Result.CopyTo(stream);
}

In your code you are getting the chunks manually by doing multiple request. 在您的代码中,您通过执行多个请求来手动获取块。 When the requested API supports chunked responses you could probably try to set the "Transfer-Encoding": "chunked" header and let HttpClient library handle the chunked response. 当请求的API支持分块响应时,您可以尝试设置"Transfer-Encoding": "chunked"标头,并让HttpClient库处理分块响应。 The header could be set on the HttpClient as following: 标头可以在HttpClient上设置,如下所示:

_client.DefaultRequestHeaders.TransferEncodingChunked = false;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM