Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails AWS S3 Download URL

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.

like image 563
franksama Avatar asked Dec 11 '22 18:12

franksama


2 Answers

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
like image 127
franksama Avatar answered Dec 29 '22 16:12

franksama


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.

like image 24
Mirror318 Avatar answered Dec 29 '22 18:12

Mirror318