问题描述:

What is the simplest way to write an binary file which is to be get remotely?

Data you have:

  • The url to the image

What I currently have is:

url = URI.parse(photo['source'])

File.open("#{RAILS_ROOT}/tmp/export/albums/#{album_name}/#{photo_name}", 'w'){ |f| f.write(Net::HTTP.start(url.host, url.port) {|http| http.get(url.path)}.body)}

网友答案:

Use open-uri, which allows you to read from a URL as though it were a file. Note the "b" is significant as a modifier to the open mode especially if you run in Windows.

require 'open-uri'
open("#{RAILS_ROOT}/tmp/export/albums/#{album_name}/#{photo_name}", 'wb') do |dest|
  open(URI.parse(photo['source']), 'rb') do |src|
    dest.write(src.read)
  end
end

Note this reads the entire file into memory before writing it out. For large files, you may want to read and write in blocks.

相关阅读:
Top