我有一个图像的URL,我想保存在本地,这样我就可以使用回形针为我的应用程序产生一个缩略图。下载和保存图像的最佳方法是什么?(我研究了ruby文件处理,但没有发现任何东西。)
当前回答
一个更短的版本:
require 'open-uri'
download = open('http://example.com/image.png')
IO.copy_stream(download, '~/image.png')
保持相同的文件名:
IO.copy_stream(download, "~/#{download.base_uri.to_s.split('/')[-1]}")
其他回答
使用Ruby 3及以上版本,使用已接受的答案,你会得到以下错误:
没有这样的文件或目录@ rb_sysopen - http://example.com/image.png (Errno: ENOENT)
解决方案是使用URI。open代替Kernel.open。例子:
require "uri"
download = URI.open('http://example.com/image.png')
File.write('~/image.png', download)
我认为这是最清晰的方式:
require 'open-uri'
File.write 'image.png', open('http://example.com/image.png').read
如果你正在使用回形针,下载从一个URL现在是自动处理。
假设你有这样的东西:
class MyModel < ActiveRecord::Base
has_attached_file :image, ...
end
在你的模型中,只需要将图像指定为URL,就像这样(故意手写):
@my_model = MyModel.new
image_url = params[:image_url]
@my_model.image = URI.parse(image_url)
您可能希望将其放在模型中的一个方法中。这也可以在Heroku的临时文件系统上正常工作。
回形针会帮你搞定。
来源:回形针文档
以上所有的例子都很棒。 在我的情况下,我只是想从图像从URL创建一个下载链接。
如果你想让它可下载(到你的下载文件夹),你可以在你的控制器中使用以下代码:
require 'open-uri'
file_type = url.to_s.split(".")[-1]
send_data open(url).read, filename: "some_name.#{file_type}", type: "image/#{file_type}", disposition: "attachment"
可能是最简单的方法:
require 'open-uri'
image_url = "https://i.imgur.com/ZWnhY9T.png"
IO.copy_stream(URI.open(image_url), 'destination.png')
推荐文章
- 了解Gemfile。锁文件
- 如何确定一个数组是否包含另一个数组的所有元素
- Rails find_or_create_by多个属性?
- Rails ActiveRecord日期之间
- 是什么导致这个ActiveRecord::ReadOnlyRecord错误?
- 最好的打印散列的方法
- Rails:dependent =>:destroy VS:dependent =>:delete_all
- 我可以在不包含Ruby模块的情况下调用实例方法吗?
- 如何将新项目添加到哈希
- 测试一个Ruby类是否是另一个类的子类
- 什么时候使用Struct vs. OpenStruct?
- 对于PostgreSQL表来说,多大才算太大?
- 数组到哈希Ruby
- 我如何让红宝石打印一个完整的回溯而不是截断一个?
- Rails:如何在Rails 4中引用CSS中的图像