Last Updated: February 25, 2016
·
2.462K
· mhdaljuboori

How to download image to local machine using rails

Today I was searching about this topic, and I found many results I want to share it with you.

Download image to download folder

Here you can use download HTML attribute in you link tag (a tag), so if you use dragonfly gem you write something similar to

<% image_url = "#{request.protocol}#{request.host_with_port}#{@user.image.url}" %>
<a href="<%= image_url %>" download="<%= @user.image_name %>" class="btn btn-block btn-primary">Download Image</a>

Here you can find more information about download attribute

Download image immediately

If you want to download image when the page open, or if you want to count how many times the image been downloaded, you can attache this code to your action

image_url = "#{request.protocol}#{request.host_with_port}#{@user.image.url}"
send_file(
  image_url,
  filename: @user.image_name,
  type: "image/png"
)

Of course you can change image type by passing format option to thumb method

@user.image.thumb("", 'format' => 'png')

send_file method not only works with images, it works with all file type, you just have to change the type option.