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

时间:2011-09-07 16:42:33

标签: ruby-on-rails ruby-on-rails-3 amazon-s3 filestream

我的问题是我在我的send_data应用程序上使用Rails 3向用户发送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时间它只需要文件大小....但是我需要的是用户正常查看下载过程,他们只会在浏览器选项卡上知道加载器发生了什么:

enter image description here

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

有什么办法可以用send_data来完成吗?

2 个答案:

答案 0 :(得分:6)

浏览器不是缓冲/延迟,而是您的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)

答案 1 :(得分:-1)

设置内容处理

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

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的指导。