Question

I've found good examples of NET::HTTP for downloading an image file, and I've found good examples of 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?

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."
Était-ce utile?

La solution 2

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> 

Autres conseils

There are more api-friendly libraries than Net::HTTP, for example 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

I like to use RestClient:

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

If you like to download a file using HTTParty you can use the following code.

resp = HTTParty.get("https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_92x30dp.png")

file = Tempfile.new
file.binmode
file.write(resp.body)
file.rewind

Further, if you want to store the file in ActiveStorage refer below code.

object.images.attach(io: file, filename: "Test.png")

Though the answers above work totally fine, I thought I would mention that it is also possible to just use the good ol' curl command 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:

# 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}`
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top