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

neilmarion picture neilmarion · Jul 20, 2011 · Viewed 18.4k times · Source

I have a link_to Rails helper that downloads a wallpaper when clicked. But the image is loading in the browser instead of being downloaded immediately.

<%= link_to "1920x1080", @download.wallpapers[1].wallpaper.url %>

But at the same time I have a link_to Rails helper that downloads a screensaver of .exe format but here it works as inteded: file being downloaded immediately.

<%= link_to "720p", @download.screensavers.first.screensaver.url %>

What should I add or do so that the images will not be opened in the browser but instead be downloaded immediately?

Thanks!

Answer

Abram picture Abram · Dec 14, 2015

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" %>