Rails 'link_to' to Download An Image Immediately Instead of Opening it in the Browser Rails 'link_to' to Download An Image Immediately Instead of Opening it in the Browser ruby-on-rails ruby-on-rails

Rails 'link_to' to Download An Image Immediately Instead of Opening it in the Browser


There is an easier way to do this with the HTML5 download attribute.

<%= link_to 'Download existing avatar', @user.avatar(:original), download: "User_#{@user.id}_avatar" %>


Instead of putting the link of the image in your tag, you can handle it in your controller. And then in your controller you can do something like

send_file @download.wallpapers[1].wallpaper.url, :type => 'image/jpeg', :disposition => 'attachment'

Read this


Generally, the cleanest way to do this is to set the appropriate header when sending the image:

Content-Disposition: attachment; filename=<file name.ext>

The send_file method will allow you to set this header appropriately if you're serving the file from the filesystem:

http://api.rubyonrails.org/classes/ActionController/Streaming.html#method-i-send_file

If the file is stored in your database, you can use send_data instead:

http://api.rubyonrails.org/classes/ActionController/Streaming.html#method-i-send_data