Skip to content

Instantly share code, notes, and snippets.

@flyingoctopus
Last active November 1, 2024 17:38
Show Gist options
  • Save flyingoctopus/2308362 to your computer and use it in GitHub Desktop.
Save flyingoctopus/2308362 to your computer and use it in GitHub Desktop.
def download_image(u)
path = 'images/%s' % u.split('/')[-1]
url = URI.parse(u)
found = false
until found
host, port = url.host, url.port if url.host && url.port
query = url.query ? url.query : ""
req = Net::HTTP::Get.new(url.path + '?' + query)
res = Net::HTTP.start(host, port) {|http| http.request(req) }
res.header['location'] ? url = URI.parse(res.header['location']) : found = true
end
open(path, "wb") do |file|
file.write(res.body)
end
path
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment