C#MVC从S3异步下载大文件 [英] C# MVC Download Big File from S3 Async

查看:409
本文介绍了C#MVC从S3异步下载大文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须从aws S3异步下载文件.我有一个锚标记,单击它会在控制器中命中一种方法进行下载.应该像其他文件下载一样,在浏览器底部开始下载文件.

I have to download a file from aws S3 async. I have a anchor tag, on clicking it a method will be hit in a controller for download. The file should be start downloading at the bottom of the browser, like other file download.

在视图中

<a href="/controller/action?parameter">Click here</a>

在控制器中

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的下载方式.
预先感谢.

The above function makes the browser to load until the file is fully downloaded. Then only the file is visible at the bottom. I cant see the how mb is downloading.
Thanks in advance.

推荐答案

您必须将ContentLength发送给客户端才能显示进度.浏览器没有有关它将接收多少数据的信息.

You must send ContentLength to client in order to display a progress. Browser has no information about how much data it will receive.

如果查看File方法使用的FileStreamResult类的源,它不会通知客户端"Content-Length". https://aspnetwebstack.codeplex.com/SourceControl/最新的#src/System.Web.Mvc/FileStreamResult.cs

If you look at source of FileStreamResult class, used by File method, it does not inform client about "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交付非公共的S3对象,而存活时间只有几秒钟.您可以简单地使用 Pre-Signed-URL

Generally this is a bad practice to download and deliver S3 file from your server. You will be charged twice bandwidth on your hosting account. Instead, you can use signed URLs to deliver non public S3 objects, with few seconds of time to live. You could simply use 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.";   
     }              
 }

只要对象没有公共读取策略,用户就不能在未签名的情况下访问对象.

As long as object do not have public read policy, objects are not accessible to users without signing.

此外,您必须在AmazonS3Client周围使用using以便快速处理网络资源,或者仅使用AmazonS3Client的一个静态实例来减少不必要的分配和取消分配.

Also, you must use using around AmazonS3Client in order to quickly dispose networks resources, or just use one static instance of AmazonS3Client that will reduce unnecessary allocation and deallocation.

这篇关于C#MVC从S3异步下载大文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆