简体   繁体   English

从http服务流式传输大文件

[英]Stream a large file from http service

I am writing a component to stream a large (4+ GB) from an HTTP service. 我正在编写一个组件,以从HTTP服务中流式传输大文件(超过4 GB)。 The component takes a URL and destination stream. 该组件采用URL和目标流。 The destination stream could be a filestream or it could be a stream that POSTS to different HTTP service, or even both. 目标流可以是文件流,也可以是POSTS到不同HTTP服务的流,或者甚至是两者。 As the author of my component, I need to do these steps until I'm done: 作为组件的作者,我需要执行以下步骤,直到完成:

  1. read a reasonable-size buffer from the HTTP stream, 从HTTP流中读取大小合理的缓冲区,
  2. write this buffer to the destination stream, 将此缓冲区写入目标流,
  3. flush the destination stream (out to disk, network, etc) 刷新目标流(到磁盘,网络等)

I should never have more than the size of the buffer of data in memory. 我决不应该超过内存中数据缓冲区的大小。

I am using flurl to make my HTTP calls to the server. 我正在使用flurl对服务器进行HTTP调用。 I've tried the following ways to make my call 我尝试了以下方式拨打电话

var stream = await flurlClient.GetStreamAsync();

This gives me back a MemoryStream, which doesn't work as it'll fill up and take up as much memory as the size of the file. 这给了我一个MemoryStream,它不起作用,因为它会填满并占用与文件大小一样多的内存。

var response = flurlClient.GetAsync();
var stream = response.Content.ReadAsStreamAsync();

Again, a memory stream. 同样,一个内存流。

var response = flurlClient.GetAsync();
var stream = new CustomFlushingSteam();
response.Content.CopyToAsync(stream);

This one looks promising, but alas, it tries to write the entire thing using a single Write() statement. 这看起来很有希望,但是可惜,它尝试使用单个Write()语句来编写整个内容。

How can I accomplish this task without blowing up my memory? 如何完成这项任务而又不消耗我的记忆? I'd prefer to use flurl, but I'm not tied to it. 我更喜欢使用flurl,但我并不局限于此。

After doing some digging, I found that the following code solves my problem: 进行一些挖掘之后,我发现以下代码解决了我的问题:

var response = flurlClient.SendAsync(
    HttpMethod.Get, null, null, HttpCompletionOption.ResponseHeadersRead);
var stream = response.Content.ReadAsStreamAsync();

In this case, the stream that comes back is no longer a memory stream but the network stream. 在这种情况下,返回的流不再是内存流,而是网络流。

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

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