How can I download a file from a URL and save it in Rails?

天大地大妈咪最大 提交于 2019-12-27 11:51:08

问题


I have a URL to an image which i want to save locally, so that I can use Paperclip to produce a thumbnail for my application. What's the best way to download and save the image? (I looked into ruby file handling but did not come across anything.)


回答1:


Try this:

require 'open-uri'
open('image.png', 'wb') do |file|
  file << open('http://example.com/image.png').read
end



回答2:


An even shorter version:

require 'open-uri'
download = open('http://example.com/image.png')
IO.copy_stream(download, '~/image.png')

To keep the same filename:

IO.copy_stream(download, "~/#{download.base_uri.to_s.split('/')[-1]}")



回答3:


If you're using PaperClip, downloading from a URL is now handled automatically.

Assuming you've got something like:

class MyModel < ActiveRecord::Base
  has_attached_file :image, ...
end

On your model, just specify the image as a URL, something like this (written in deliberate longhand):

@my_model = MyModel.new
image_url = params[:image_url]
@my_model.image = URI.parse(image_url)

You'll probably want to put this in a method in your model. This will also work just fine on Heroku's temporary filesystem.

Paperclip will take it from there.

source: paperclip documentation




回答4:


I think this is the clearest way:

require 'open-uri'

File.write 'image.png', open('http://example.com/image.png').read



回答5:


Check out Net::HTTP in the standard library. The documentation provides several examples on how to download documents using HTTP.



来源:https://stackoverflow.com/questions/2515931/how-can-i-download-a-file-from-a-url-and-save-it-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!