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

Build a link_to to download an image.


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 '', :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 = {})



Instead of send_file you can use send_data method as follows:

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


All code examples are avaiable here on github:






    Running a bit slow fetching the file on my localhost though

  • Ramesh Raj

    awsome !!!
    it’s working fine.