Search code examples
rubynet-http

How to download image from url?


I have an url: http://limg.imgsmail.ru/splash/v/i/icons.v16.14afed9dda24aad97c9dc5bf24396fbd6ede4e22.png and if I try to get this png file with 'net/http'

Net::HTTP.start('www.limg.imgsmail.ru') {|http|
        rest = http.get('/splash/v/i/icons.v16.14afed9dda24aad97c9dc5bf24396fbd6ede4e22.png')
        open('1.png', 'wb') {|file| file.write(rest.body)}
    }

I have an error: SocketError: getaddrinfo: Name or service not known. Why is this happening? The full link is correct! How can I download such files?


Solution

  • Try this:

    require "open-uri"
    
    File.open('1.png', 'wb') do |fo|
      fo.write open("http://limg.imgsmail.ru/splash/v/i/icons.v16.14afed9dda24aad97c9dc5bf24396fbd6ede4e22.png").read 
    end
    

    Note: I have removed www from your url as with that url is not working. this url works fine.