How to download an image file via HTTP into a temp file? How to download an image file via HTTP into a temp file? ruby ruby

How to download an image file via HTTP into a temp file?


There are more api-friendly libraries than Net::HTTP, for example httparty:

require "httparty"url = "https://upload.wikimedia.org/wikipedia/commons/thumb/9/91/DahliaDahlstarSunsetPink.jpg/250px-DahliaDahlstarSunsetPink.jpg"File.open("/tmp/my_file.jpg", "wb") do |f|   f.write HTTParty.get(url).bodyend


require 'net/http'require 'tempfile'require 'uri'def save_to_tempfile(url)  uri = URI.parse(url)  Net::HTTP.start(uri.host, uri.port) do |http|    resp = http.get(uri.path)    file = Tempfile.new('foo', Dir.tmpdir, 'wb+')    file.binmode    file.write(resp.body)    file.flush    file  endendtf = save_to_tempfile('http://a.fsdn.com/sd/topics/transportation_64.png')tf # => #<File:/var/folders/sj/2d7czhyn0ql5n3_2tqryq3f00000gn/T/foo20130827-58194-7a9j19> 


I like to use RestClient:

file = File.open("/tmp/image.jpg", 'wb' ) do |output|  output.write RestClient.get("http://image_url/file.jpg")end