Link to download an image as attachment in Rails (send_file and remote files)

January 1, 2013 · Posted in Development 

Build a link_to to download an image.

send_file

send_file method can be used in a controller to download the file in browser:

send_file '/path/to/file', :type => 'image/jpeg', :disposition => 'attachment'

 

But in case when you have an url for the remote file (for example, an image stored in amazon cloud storage like Amazon S3) then this code

send_file 'http://someserver.com/path/to/file', :type => 'image/jpeg', :disposition => 'attachment'

will give an error “Cannot read file http://..”.

According to this documentation send_file expects the first parameter to be the path to your file, i.e. the file should be stored locally on this server.

send_file(path, options = {})

 

send_data

Instead of send_file you can use send_data method as follows:

require 'open-uri'
url = 'http://someserver.com/path/../filename.jpg'
data = open(url).read
send_data data, :disposition => 'attachment', :filename=>"photo.jpg"

 

All code examples are avaiable here on github:

https://gist.github.com/4430975

 

 

Comments

  • MACMAN

    BEAUTIFUL! THANK YOU!

  • MACMAN

    Running a bit slow fetching the file on my localhost though

  • Ramesh Raj

    awsome !!!
    it’s working fine.