Ruby on Rails AWS S3 Download URL

…衆ロ難τιáo~ 提交于 2020-01-14 03:32:08

问题


How can I form a url link for a user so that when the user clicks on the link, it forces them to download the AWS S3 object?

I've seen these two solutions: Using send_file to download a file from Amazon S3? and Using send_file to download a file from Amazon S3? however, they seem to reference an old AWS S3 v1 SDK and there does not seem to be a url_for in the v2 AWS S3 SDK.

Thanks.


回答1:


Ended up using the following code snippet to solve. Hope this helps others.

presigner = Aws::S3::Presigner.new
    url = presigner.presigned_url(:get_object, #method
                    bucket: ENV['S3_BUCKET'], #name of the bucket
                    key: s3_key, #key name
                    expires_in: 7.days.to_i, #time should be in seconds
                    response_content_disposition: "attachment; filename=\"#{filename}\""
                    ).to_s



回答2:


Here's what I got:

def user_download_url(s3_filename, download_filename=nil)
  s3_filename = s3_filename.to_s # converts pathnames to string
  download_filename ||= s3_filename.split('/').last
  url_options = {
    expires_in:                   60.minutes,
    response_content_disposition: "attachment; filename=\"#{download_filename}\""
  }
  object = bucket.object(s3_filename)
  object.exists? ? object.presigned_url(:get, url_options).to_s : nil
end

def bucket
  @bucket ||= Aws::S3::Resource.new(region: ENV['AWS_REGION']).bucket(ENV['AWS_S3_BUCKET'])
end

To create a link for downloading, simply put redirect_to user_download_url(s3_file_path) in a controller action, and create a link to that controller action.



来源:https://stackoverflow.com/questions/35258433/ruby-on-rails-aws-s3-download-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!