How do I download a picture using Ruby?

2019-01-10 19:08发布

I want to download this picture using Ruby. How do I do that?

http://farm1.static.flickr.com/92/218926700_ecedc5fef7_o.jpg

I am using Mac OS.

标签: ruby http
8条回答
再贱就再见
2楼-- · 2019-01-10 19:55

To make things cleaner I would suggest you use the File's name itself when you save the image. I had an issue saving bulk images because they were not formated correctly. The images were saved like this:

#pic.jpg(1)
#pic.jpg(2)
#etc.

Thats why you should probably use the image name as the file name like this:

src = 'http://www.asite.com/pic.jpg'    
agent.get(src).save "#{folder}/#{File.basename(src)}"

File.basename takes the image url and just returns the the actual image name:

File.basename("http://www.asite.com/pic.jpg")
# returns the image name
pic.jpg
查看更多
劫难
3楼-- · 2019-01-10 20:03

require "open-uri"

open("your-url") {|f|
   File.open("whatever_file.jpg","wb") do |file|
     file.puts f.read
   end
}


查看更多
登录 后发表回答