简体   繁体   中英

How do you write an image at a url to your filesystem in Ruby?

If there is an image at a public url, how would I write and save it to my local filesystem using Ruby?

require "open-uri"

open("http://www.whatever.com/x.png") do |hnd|
  File.open("x.png","wb") {|file| file.puts hnd.read }
end

EDIT:

This allows you to use open to load a website, and treat it as normal file handle:

require "open-uri"

This loads your image, and passes a handle to the page body, as the parameter hnd :

open("http://www.whatever.com/x.png") do |hnd|

This opens a file in binary mode ( needed on Windows systems ), and writes the page's content into it:

File.open("x.png","wb") {|file| file.puts hnd.read }

The content is obtained via the read method, which tries to read it completely before writing it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM