Download a list of images over https in Ruby

15 Apr 2008

Long post title.

Today I found myself with a text file of image names that needed to be downloaded from a site. This is how I did it:

require 'net/http'
require "net/https"'', 443)
@http.use_ssl = true

# open file with file names for reading only - my file names were one per line
image_list ="imagenames.txt", "r")  

#start our web session:
@http.start() do |http|
  image_list.each do |file_name|
    # remove any extra \r or \n chars

    #only download if we don't already have it:
    unless File.exists? "images/#{file_name}"
      # status message:
      print "downloading #{file_name}..."

      # set up the request
      req ="/images/#{file_name}")
      response = http.request(req)
      # write the binary data to the local file of the same name:
      open("images/#{file_name}","wb").write( response.body )

      puts "DONE!"
      puts "skipping: #{file_name}"


Many thanks to these articles: