如何强制send_data在浏览器中下载文件?

我的问题是我在我的Rails 3应用程序上使用send_data向用户发送一个来自AWS S3服务的文件

 Base.establish_connection!( :access_key_id => 'my_key', :secret_access_key => 'my_super_secret_key') s3File = S3Object.find dir+filename, "my_unique_bucket" send_data(open(s3File.url).read,:filename=>filename, :disposition => 'attachment') 

但似乎浏览器正在缓冲文件,并且在缓冲之前将文件下载发送到下载,不需要时间下载,但在buffering时它只需要文件大小….但我需要的是用户查看正常下载过程中,他们只会在浏览器选项卡上知道加载器发生了什么:

在此处输入图像描述

他们宁愿看到一个下载过程,我想要弄清楚那里发生了什么

有没有办法用send_data做到这send_data

这不是浏览器的缓冲/延迟,而是你的Ruby服务器代码。

您将从S3下载整个文件,然后将其作为附件发送回用户。

使用重定向直接从S3向您的用户提供此内容可能更好。 以下是构建临时访问URL的链接,该URL允许在短时间内使用给定令牌进行下载:

http://docs.amazonwebservices.com/AmazonS3/latest/dev/S3_QSAuth.html

 Base.establish_connection!( :access_key_id => 'my_key', :secret_access_key => 'my_super_secret_key') s3File = S3Object.find dir+filename, "my_unique_bucket" redirect_to s3File.url(:expires_in => 30) 

设置您的内容处置

您需要设置S3url的内容配置才能下载,而不是在浏览器中打开。 这是我的基本实现:

attachment视为您的s3file

在你的attachment.rb

 def download_url s3 = AWS::S3.new.buckets[ 'bucket_name' ] s3.url_for( :read, expires_in: 60.minutes, use_ssl: true, response_content_disposition: "attachment; filename='#{file_name}'" ).to_s end 

在你的意见

 <%= link_to 'Download Avicii by Avicii', attachment.download_url %> 

感谢guilleva的指导。

Interesting Posts