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

Dogweather picture Dogweather · Aug 27, 2013 · Viewed 22.8k times · Source

I've found good examples of NET::HTTP for downloading an image file, and I've found good examples of creating a temp file. But I don't see how I can use these libraries together. I.e., how would the creation of the temp file be worked into this code for downloading a binary file?

require 'net/http'

Net::HTTP.start("somedomain.net/") do |http|
    resp = http.get("/flv/sample/sample.flv")
    open("sample.flv", "wb") do |file|
        file.write(resp.body)
    end
end
puts "Done."

Answer

fguillen picture fguillen · Aug 27, 2013

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).body
end