我有一个图像的URL,我想保存在本地,这样我就可以使用回形针为我的应用程序产生一个缩略图。下载和保存图像的最佳方法是什么?(我研究了ruby文件处理,但没有发现任何东西。)
试试这个:
require 'open-uri'
open('image.png', 'wb') do |file|
file << open('http://example.com/image.png').read
end
如果你正在使用回形针,下载从一个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的临时文件系统上正常工作。
回形针会帮你搞定。
来源:回形针文档
一个更短的版本:
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]}")
我认为这是最清晰的方式:
require 'open-uri'
File.write 'image.png', open('http://example.com/image.png').read
可能是最简单的方法:
require 'open-uri'
image_url = "https://i.imgur.com/ZWnhY9T.png"
IO.copy_stream(URI.open(image_url), 'destination.png')
以上所有的例子都很棒。 在我的情况下,我只是想从图像从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"
使用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)
推荐文章
- 在rails redirect_to中传递参数
- Rails new vs create
- Rails has_many的别名
- 如何记录Ruby代码?
- Ruby:包含的反义词是什么?Ruby数组?
- 想要在Rails中找到没有关联记录的记录
- helper和helper_method做什么?
- 如何回滚只是一个步骤使用耙db:迁移
- 在Ruby中,proc和lambda有什么区别?
- 如何传递参数到一个Rake任务与环境在Rails?
- 获取当前正在执行的方法的名称
- 如何在Rails中计算相对时间?
- 如何在Rails迁移中将可空列更改为不可空列?
- 在Ruby中使用范围填充数组的正确方法
- “for”和“each”在Ruby中