Download File from S3 to Rails 4 App

Download file from S3 to Rails 4 app

The aws-sdk v2 gem provides a simple interface for downloading objects from Amazon S3.

require 'aws-sdk'

s3 = Aws::S3::Resource.new(
region: 'us-east-1',
access_key_id: '...',
secret_access_key: '...'
)

s3.bucket('bucket-name').object('key').get(response_target: '/path/to/file')

Rails: allow download of files stored on S3 without showing the actual S3 URL to user

Yes, this is possible - just fetch the remote file with Rails and either store it temporarily on your server or send it directly from the buffer. The problem with this is of course the fact that you need to fetch the file first before you can serve it to the user. See this thread for a discussion, their solution is something like this:

#environment.rb
require 'open-uri'

#controller
def index
data = open(params[:file])
send_data data, :filename => params[:name], ...
end

This issue is also somewhat related.

Allowing User to Download File from S3 Storage

To make this work, I've just added a new action in the controller, so in your case it could be:

#routes
resources :events do
member { get :download }
end

#index
<%= link_to 'Download Creative', download_event_path(event), class: "btn btn-info" %>

#events_controller
def download
data = open(event.creative_url)
send_data data.read, :type => data.content_type, :x_sendfile => true
end

EDIT:
the correct solution for download controller action can be found here (I've updated the code above): Force a link to download an MP3 rather than play it?

Using send_file to download a file from Amazon S3?

In order to send a file from your web server,

  • you need to download it from S3 (see @nzajt's answer) or

  • you can redirect_to @attachment.file.expiring_url(10)

Downloading S3 files(objects) using aws-sdk for ruby in rails

You'd probably be better off providing a url for users to download directly from S3 rather than trying to stream the file through your Rails app.

The aws-sdk provides the url_for method to accomplish this: http://docs.aws.amazon.com/AWSRubySDK/latest/AWS/S3/S3Object.html#url_for-instance_method. It takes a bunch of options for expiration, security, caching, etc. A basic example:

<td><%= link_to "Download", file.url_for(:read) %></td>

--EDIT--

To access the url_for method in the view, you'll need references to the s3 objects. So in your controller, you want to collect objects from the leaf nodes, not keys:

@root_files = bucket.as_tree.children.select(&:leaf?).collect(&:object)


Related Topics



Leave a reply



Submit