gpt4 book ai didi

c# - 如何使用 Amazon S3 ResponseStream 返回 FileResult?

转载 作者:行者123 更新时间:2023-11-30 20:29:06 26 4
gpt4 key购买 nike

使用 AWSSDK.S3 nuget 包,我试图返回一个从 S3 存储桶中检索到的文件。我的出发点是基于此 SO answer 中给出的示例.

示例 Controller 代码:

public FileResult GetFile(Guid id)
{
// no using block as it will be disposed of by the File method
var amazonResponse = _foo.GetAmazonResponseWrapper(_user, id);
// set Response content-length header
// set Response content-type header

var bufferSize = 1024;
var buffer = new byte[bufferSize];
int bytesRead;

while ((bytesRead = amazonResponse.ResponseStream.Read(buffer, 0, buffer.Length)) > 0 && Response.IsClientConnected)
{
Response.OutputStream.Write(buffer, 0, bytesRead);
Response.OutputStream.Flush();
buffer = new byte[bufferSize];
}

// this will not work (can't read from this stream)
return File(Response.OutputStream, "text/plain", "bar.txt");
}

如果我写入在 while 循环中创建和使用的 MemoryStream,我将得到一个文件,但不会有任何内容。

我发现获取文件内容的唯一方法是像这样在流上调用 .ToArray():

return File(memStream.ToArray(), "text/plain", "foo.txt");

有没有一种方法可以将文件实际流式传输到浏览器,而无需将其加载到网络服务器的内存中?

最佳答案

只是向前传递流

public FileResult GetFile(Guid id) {
// no using block as it will be disposed of by the File method
var amazonResponse = _foo.GetAmazonResponseWrapper(_user, id);
return File(amazonResponse.ResponseStream, "text/plain", "bar.txt");
}

您已经证明可以从响应流中读取。然后只需传递响应流,File 结果将读取它并返回响应。

关于c# - 如何使用 Amazon S3 ResponseStream 返回 FileResult?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46595222/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com