1

I have to make a request to a page www.example.com/xls_file which sends a file. I have Nokogiri and Mechanize available. How would I download the file and save it locally?

def file
  grab_file if !File.exists?("sales_data.csv")
  File.open("sales_data.csv")
end

def grab_file
  # What do I do here?
  # Nokogiri::HTML(open("http://www.example.com/xls_file"))
end
bigpotato
  • 26,262
  • 56
  • 178
  • 334
  • 1
    Check out this [SO answer](http://stackoverflow.com/questions/2263540/how-do-i-download-a-binary-file-over-http). It has a bunch of options, including using `net/http` or `open-uri` to download the file. – orde Sep 24 '14 at 15:22

1 Answers1

2
require 'open-uri'

File.open('any_name_here.xls', 'wb') do |file|
 file << open('http://www.example.com/xls_file.xls').read
end

If the site you want to get the file from starts with https:// then you might want to add the following things to avoid Ruby reporting SSL errors:

require 'open-uri'
require 'openssl'

File.open('any_name_here.xls', 'wb') do |file|
  file << open('https://www.example.com/xls_file.xls', ssl_verify_mode: OpenSSL::SSL::VERIFY_NONE).read
end
daremkd
  • 8,244
  • 6
  • 40
  • 66