Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using send_file to download a file from Amazon S3?

I have a download link in my app from which users should be able to download files which are stored on s3. These files will be publicly accessible on urls which look something like

https://s3.amazonaws.com/:bucket_name/:path/:to/:file.png 

The download link hits an action in my controller:

class AttachmentsController < ApplicationController   def show     @attachment = Attachment.find(params[:id])     send_file(@attachment.file.url, disposition: 'attachment')   end end 

But I get the following error when I try to download a file:

ActionController::MissingFile in AttachmentsController#show  Cannot read file https://s3.amazonaws.com/:bucket_name/:path/:to/:file.png Rails.root: /Users/user/dev/rails/print  Application Trace | Framework Trace | Full Trace app/controllers/attachments_controller.rb:9:in `show' 

The file definitely exists and is publicly accessible at the url in the error message.

How do I allow users to download S3 files?

like image 907
David Tuite Avatar asked Sep 05 '12 09:09

David Tuite


People also ask

How do I download data from aws S3?

You can download an object from an S3 bucket in any of the following ways: Select the object and choose Download or choose Download as from the Actions menu if you want to download the object to a specific folder. If you want to download a specific version of the object, select the Show versions button.

How do I download from S3 bucket to local using command line?

You can use cp to copy the files from an s3 bucket to your local system. Use the following command: $ aws s3 cp s3://bucket/folder/file.txt . To know more about AWS S3 and its features in detail check this out!


1 Answers

You can also use send_data.

I like this option because you have better control. You are not sending users to s3, which might be confusing to some users.

I would just add a download method to the AttachmentsController

def download   data = open("https://s3.amazonaws.com/PATTH TO YOUR FILE")    send_data data.read, filename: "NAME YOU WANT.pdf", type: "application/pdf", disposition: 'inline', stream: 'true', buffer_size: '4096'  end  

and add the route

get "attachments/download" 
like image 179
nzajt Avatar answered Oct 05 '22 03:10

nzajt