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

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

 

 

3 thoughts on “Link to download an image as attachment in Rails (send_file and remote files)”

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>