ruby 如何通过 HTTP 将图像文件下载到临时文件中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18474483/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 06:08:56  来源:igfitidea点击:

How to download an image file via HTTP into a temp file?

rubyurinet-http

提问by Dogweather

I've found good examplesof NET::HTTP for downloading an image file, and I've found good examplesof creating a temp file. But I don't see how I can use these libraries together. I.e., how would the creation of the temp file be worked into this code for downloading a binary file?

我发现很好的例子NET :: HTTP的下载一个图像文件,我已经找到了很好的例子创建一个临时文件。但是我不知道如何一起使用这些库。即,如何将临时文件的创建用于下载二进制文件的代码中?

require 'net/http'

Net::HTTP.start("somedomain.net/") do |http|
    resp = http.get("/flv/sample/sample.flv")
    open("sample.flv", "wb") do |file|
        file.write(resp.body)
    end
end
puts "Done."

采纳答案by maerics

require 'net/http'
require 'tempfile'
require 'uri'

def save_to_tempfile(url)
  uri = URI.parse(url)
  Net::HTTP.start(uri.host, uri.port) do |http|
    resp = http.get(uri.path)
    file = Tempfile.new('foo', Dir.tmpdir, 'wb+')
    file.binmode
    file.write(resp.body)
    file.flush
    file
  end
end

tf = save_to_tempfile('http://a.fsdn.com/sd/topics/transportation_64.png')
tf # => #<File:/var/folders/sj/2d7czhyn0ql5n3_2tqryq3f00000gn/T/foo20130827-58194-7a9j19> 

回答by fguillen

There are more api-friendly libraries than Net::HTTP, for example httparty:

有比 更 api 友好的库Net::HTTP,例如httparty

require "httparty"

url = "https://upload.wikimedia.org/wikipedia/commons/thumb/9/91/DahliaDahlstarSunsetPink.jpg/250px-DahliaDahlstarSunsetPink.jpg"

File.open("/tmp/my_file.jpg", "wb") do |f| 
  f.write HTTParty.get(url).body
end

回答by Daniel Cukier

I like to use RestClient:

我喜欢使用 RestClient:

file = File.open("/tmp/image.jpg", 'wb' ) do |output|
  output.write RestClient.get("http://image_url/file.jpg")
end

回答by Shahzeb Khan

Though the answers above work totally fine, I thought I would mention that it is also possible to just use the good ol' curlcommand to download the file into a temporary location. This was the use case that I needed for myself. Here's a rough idea of the code:

虽然上面的答案完全正常,但我想我会提到也可以只使用 good ol'curl命令将文件下载到临时位置。这是我自己需要的用例。这是代码的粗略概念:

# Set up the temp file:
file = Tempfile.new(['filename', '.jpeg'])

#Make the curl request:
url = "http://example.com/image.jpeg"
curlString = "curl --silent -X GET \"#{url}\" -o \"#{file.path}\""
curlRequest = `#{curlString}`