1
使用AWSSDK.S3 nuget包,我试图返回从S3存储桶检索到的文件。我的出发点是基于此SO answer中给出的示例。如何使用Amazon S3 ResponseStream返回FileResult?
例控制器代码:
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");
}
如果我写一个MemoryStream
我创建并在while
循环使用,我会得到一个文件,但不会有任何内容。
我发现文件中获得内容的唯一方法是调用.ToArray()
在流像这样:
return File(memStream.ToArray(), "text/plain", "foo.txt");
是否有实际流的文件浏览器的方式,而不加载到Web服务器的内存?
这看起来像是其中一个“它非常简单,它必须以这种方式工作”的情况。我不确定使用中间流的原因,因为我是AWS新手。我明天再说一遍这个问题,谢谢! – Jecoms
当然。它似乎是使用HttpResponse对象的控制器代码。 – Jecoms
@Jecoms,我纠正了。这可能是早期版本。 – Nkosi