Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

uri

ruby

net-http

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."
like image 895
Dogweather Avatar asked Aug 27 '13 20:08

Dogweather


2 Answers

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
like image 142
fguillen Avatar answered Nov 19 '22 08:11

fguillen


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
  end
end

tf = save_to_tempfile('http://a.fsdn.com/sd/topics/transportation_64.png')
tf # => #<File:/var/folders/sj/2d7czhyn0ql5n3_2tqryq3f00000gn/T/foo20130827-58194-7a9j19> 
like image 43
maerics Avatar answered Nov 19 '22 09:11

maerics