Rails 直接从 S3 下载文件,content-disposition = attachment?

Rails download file direct from S3 with content-disposition = attachment?

这是我的控制器

控制器

def download
    data = open(@attachment.file.url).read

    @attachment.clicks = @attachment.clicks.to_i + 1
    @attachment.save
    send_data data, :type => @attachment.content_type, :filename => @attachment.name
  end

示例:

@attachment.file.url = "http://my_bucket.cloudfront.net/uploads/attachment/file/50/huge_file.pptx" 

我这样做了,但是如果 @attachment 是一个巨大的文件(例如 300MB),我的服务器就会崩溃。 我想让用户直接从我的 AWS 服务器在浏览器中下载文件吗?

2) 提示:您建议从 S3(文件的存储位置)还是使用 CloudFront 下载文件?

如果您使用载波 gem,您可以试试这个来跟踪点击次数

def download
  @attachment.clicks.to_i += 1
  @attachment.save
  redirect_to @attachment.file.url(query: {"response-content-disposition" => "attachment;"})
end

参考文献:

  • Rails carrierwave S3 get url with Content-Disposition header