wikiti
6/21/2017 - 9:37 AM

Download a file from Ruby

Download a file from Ruby

# Download a file with 'open-uri':
require 'open-uri'
download = open('http://url.to/file')

# Use argument `http_basic_authentication` for basic auth:
download = open(
  'http://url.to/file',
  http_basic_authentication: ['user', 'password']
)

# Extract the filename from http headers:
filename = download.meta['content-disposition'].match(/filename=(\"?)(.+)\1/)[2]

# Save it to a file; use 'w' for plain text, 'wb' for binary:
open("path/to/folder/#{filename}", 'wb') do |file|
  file << download.read
end

# Close the downloaded file handler:
download.close