Question

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.

Était-ce utile?

La 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.

Autres conseils

You can save the file anywhere in the public folder of the rails application. The right path would be something like this #{Rails.root}/public/myimages/<image_name>.png and then you can refer to it with a URL like this http://localhost:3000/myimages/<image_name>.png. Hope this will help.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top