Jec*_*oms 2 c# asp.net-mvc stream amazon-s3
使用 AWSSDK.S3 nuget 包,我尝试返回从 S3 存储桶中检索到的文件。我的出发点基于此SO answer 中给出的示例。
示例控制器代码:
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");
}
Run Code Online (Sandbox Code Playgroud)
如果我写入一个MemoryStreamI create 并在while循环中使用,我会得到一个文件,但不会有任何内容。
我发现在文件中获取内容的唯一方法是.ToArray()像这样调用流:
return File(memStream.ToArray(), "text/plain", "foo.txt");
Run Code Online (Sandbox Code Playgroud)
有没有办法将文件实际流式传输到浏览器而不将其加载到 Web 服务器的内存中?
只是向前传递流
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");
}
Run Code Online (Sandbox Code Playgroud)
您已经证明您可以从响应流中读取。然后只需传递响应流,文件结果将读取它并返回响应。
| 归档时间: |
|
| 查看次数: |
1048 次 |
| 最近记录: |