We Feature Like No Other

Japanese Modern Popular Culture now has a home

May 30, 2007

Ruby - How to download an image with Net::HTTP

A Fine Entry by
geoxgeox
» » » »

This is a little out of topic with the usual posts, but I’m sure it’ll help out a few people.

I’ve been playing around with ruby on rails for a while, and I want to be able to download binary files easily. Here’s how you can do it:

require 'net/http'
require 'uri'

fh = File.new("temp.jpg","wb")
res = Net::HTTP.get_response URI.parse('complete_url_to_binary_file')

if res.message == "OK"
  fh.print res.body
end

fh.close

Don’t forget the “wb” when you create your file, in order to write to the file in binary mode. Took me a while to figure it all, so I thought I might share it!

Leave a Comment