如何从Ruby上的URI下载图像

时间:2015-02-20 09:58:40

标签: ruby

我想使用Ruby从URI下载图像,但它给了我这个错误。

我的代码:

 def image_from_json
   path = URI(@path)
   puts "path : #{path}"
   content = Net::HTTP.get(path)
   json = JSON.parse(content)
   url = URI(json["application"]["parameters"]["app_icon"])
   puts "url : #{url}"
   #image = Net::HTTP.get(url)
   Net::HTTP.start(url) do |http|
     resp = http.get("/Picto_Balmoral1.png")
     open("/Picto_Balmoral1.png" ,"wb") do |file|
       file.write(resp.body)
     end
   end
 end

我的错误:

/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/net/http.rb:878:in `initialize': no implicit conversion of URI::HTTP into String (TypeError)

那我怎么能把这个转换成String?

1 个答案:

答案 0 :(得分:1)

请尝试使用open-uri。它是Rubys标准库的一部分,但您必须手动require

require 'open-uri'

def image_from_json
  path = URI(@path)

  puts "path : #{path}"

  content = Net::HTTP.get(path)
  json = JSON.parse(content)
  url = URI(json["application"]["parameters"]["app_icon"])

  puts "url : #{url}"

  open(url) do |remote_file|
    File.open("/Picto_Balmoral1.png", "wb") do |local_file|
      local_file.write(remote_file.read)
    end
  end
end