Ruby-on-rails 如何从 URL 下载文件并将其保存在 Rails 中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2515931/
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
How can I download a file from a URL and save it in Rails?
提问by Alok Swain
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.)
我有一个指向要保存在本地的图像的 URL,以便我可以使用 Paperclip 为我的应用程序生成缩略图。下载和保存图像的最佳方法是什么?(我研究了 ruby 文件处理,但没有遇到任何问题。)
回答by Levi
Try this:
尝试这个:
require 'open-uri'
open('image.png', 'wb') do |file|
file << open('http://example.com/image.png').read
end
回答by Clemens Helm
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]}")
回答by superluminary
If you're using PaperClip, downloading from a URL is now handled automatically.
如果您使用的是 PaperClip,现在会自动处理从 URL 下载。
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):
在您的模型上,只需将图像指定为 URL,如下所示(用刻意的手写方式编写):
@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.
您可能希望将其放入模型中的方法中。这在 Heroku 的临时文件系统上也能正常工作。
Paperclip will take it from there.
回形针会从那里拿走它。
source: paperclip documentation
来源:回形针文档
回答by Sage Ross
I think this is the clearest way:
我认为这是最清晰的方法:
require 'open-uri'
File.write 'image.png', open('http://example.com/image.png').read

![Ruby-on-rails Rails:一次添加多个 flash[:notice] 的简单方法](/res/img/loading.gif)