我必须从 aws S3 async 下载文件。我有一个 anchor 标记,单击它会在 Controller 中点击一个方法进行下载。该文件应该在浏览器底部开始下载,就像其他文件下载一样。
在 View 中
<a href="/controller/action?parameter">Click here</a>
在 Controller 中
public void action()
{
try
{
AmazonS3Client client = new AmazonS3Client(accessKeyID, secretAccessKey);
GetObjectRequest req = new GetObjectRequest();
req.Key = originalName;
req.BucketName = ConfigurationManager.AppSettings["bucketName"].ToString() + DownloadPath;
FileInfo fi = new FileInfo(originalName);
string ext = fi.Extension.ToLower();
string mimeType = ReturnmimeType(ext);
var res = client.GetObject(req);
Stream responseStream = res.ResponseStream;
Stream response = responseStream;
return File(response, mimeType, downLoadName);
}
catch (Exception)
{
failure = "File download failed. Please try after some time.";
}
}
上述函数使浏览器加载直到文件完全下载。然后只有文件在底部可见。我看不到 mb 是如何下载的。
提前致谢。
最佳答案
您必须向客户端发送ContentLength
以显示进度。浏览器没有关于它将接收多少数据的信息。
如果您查看由 File
方法使用的 FileStreamResult
类的源代码,它不会通知客户端有关“Content-Length”的信息。 https://aspnetwebstack.codeplex.com/SourceControl/latest#src/System.Web.Mvc/FileStreamResult.cs
替换这个,
return File(response, mimeType, downLoadName);
与
return new FileStreamResultEx(response, res.ContentLength, mimeType, downloadName);
public class FileStreamResultEx : ActionResult{
public FileStreamResultEx(
Stream stream,
long contentLength,
string mimeType,
string fileName){
this.stream = stream;
this.mimeType = mimeType;
this.fileName = fileName;
this.contentLength = contentLength;
}
public override void ExecuteResult(
ControllerContext context)
{
var response = context.HttpContext.Response;
response.BufferOutput = false;
response.Headers.Add("Content-Type", mimeType);
response.Headers.Add("Content-Length", contentLength.ToString());
response.Headers.Add("Content-Disposition","attachment; filename=" + fileName);
using(stream) {
stream.CopyTo(response.OutputStream);
}
}
}
备选
通常,从您的服务器下载和传送 S3 文件是一种不好的做法。您的托管帐户将被收取两倍的带宽费用。相反,您可以使用签名 URL 来交付非公共(public) S3 对象,只有几秒钟的生存时间。您可以简单地使用 Pre-Signed-URL
public ActionResult Action(){
try{
using(AmazonS3Client client =
new AmazonS3Client(accessKeyID, secretAccessKey)){
var bucketName =
ConfigurationManager.AppSettings["bucketName"]
.ToString() + DownloadPath;
GetPreSignedUrlRequest request1 =
new GetPreSignedUrlRequest(){
BucketName = bucketName,
Key = originalName,
Expires = DateTime.Now.AddMinutes(5)
};
string url = client.GetPreSignedURL(request1);
return Redirect(url);
}
}
catch (Exception)
{
failure = "File download failed. Please try after some time.";
}
}
只要对象没有公共(public)读取策略,用户就无法在不签名的情况下访问对象。
此外,您必须在 AmazonS3Client
周围使用 using
以便快速处理网络资源,或者只使用 AmazonS3Client
的一个静态实例,它将减少不必要的分配和释放。
关于C# MVC 从 S3 异步下载大文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41762520/