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:

[codesyntax lang=”rails”]

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

[/codesyntax]

 

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

[codesyntax lang=”rails”]

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

[/codesyntax]

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:

[codesyntax lang=”rails”]

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

[/codesyntax]

 

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>