Search code examples
ruby-on-railsrubydownloadtemporary-files

How to download image from url and display in view


I am trying to download an image and displaying it in a view in rails.

The reason why I want to download it is because the url contains some api-keys which I am not very fond of giving away.

The solution I have tried thus far is the following:

#Model.rb file
def getUrlMethod
   someUrlToAPNGfile = "whatever.png"
   file = Tempfile.new(['imageprependname', '.png'], :encoding => "ascii-8bit")
   file.write(open(data).read)
   return "#{Rails.application.config.action_mailer.default_url_options[:host]}#{file.path}"
end
#This seems to be downloading the image just fine. However the url that is returned does not point to a legal place

Under development I get this URL for the picture: localhost:3000/var/folders/18/94qgts592sq_yq45fnthpzxh0000gn/T/imageprependname20130827-97433-10esqxh.png

That image link does not point anywhere useful.

My theories to what might be wrong is:

  1. The tempfile is deleted before the user can request it
  2. The url points to the wrong place
  3. The url is not a legal route in the routes file

A am currently not aware of any way to fix either of these. Any help?


By the way: I do not need to store the picture after I have displayed it, as it will be changing constantly from the source.


Solution

  • I can think of two options:

    First, embed the image directly in the HTML documents, see http://www.techerator.com/2011/12/how-to-embed-images-directly-into-your-html/ http://webcodertools.com/imagetobase64converter

    Second, in the HTML documents, write the image tag as usual:

    <img src="/remote_images/show/whatever.png" alt="whatever" />
    

    Then you create a RemoteImages controller to process the requests for images. In the action show, the images will be downloaded and returned with send_data.

    You don't have to manage temporary files with both of these options.