我有一个指向图片的 URL,想要将它保存到本地,这样我就可以使用 Paperclip 来为我的应用程序生成缩略图。下载和保存图片的最佳方式是什么?(我研究了 Ruby 文件处理,但没有找到任何相关内容。)
我该如何在本地下载并保存这张图片呢?我想用 Paperclip 为我的应用生成缩略图。我有一个指向图片的 URL,想要将它保存到本地,这样我就可以使用 Paperclip 来为我的应用程序生成缩略图。下载和保存图片的最佳方式是什么?(我研究了 Ruby 文件处理,但没有找到任何相关内容。)
我该如何在本地下载并保存这张图片呢?我想用 Paperclip 为我的应用生成缩略图。试一下这个:
require 'open-uri'
open('image.png', 'wb') do |file|
file << open('http://example.com/image.png').read
end
更简短的版本:
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]}")
open
时,Rubocop会发出安全警告。我将其替换为URI.parse(url).open
。在此处了解有关该警告的更多信息:https://www.rubydoc.info/gems/rubocop/RuboCop/Cop/Security/Open - Joshua Pinteropen
对我不起作用,必须使用 URI.open
。 - xerufclass MyModel < ActiveRecord::Base
has_attached_file :image, ...
end
@my_model = MyModel.new
image_url = params[:image_url]
@my_model.image = URI.parse(image_url)
您可能希望将此代码放在模型的方法中。这也可以在Heroku的临时文件系统上正常工作。
接下来,Paperclip将处理它。
来源:Paperclip文档
我认为这是最清晰的方式:
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')
copy_stream()
的第一个参数**URI.open(img_url)**,如果我不用URI.open()
包装img_url
,就会出现以下错误:No such file or directory @ rb_sysopen
。 - lee mcMcartney请查看标准库中的Net::HTTP,该文档提供了多个使用HTTP下载文档的示例。
Kernel#open
不仅可以通过在管道符号前缀(例如open("| ls")
)来启用文件访问,还可以启用进程调用。因此,通过将变量输入到Kernel#open
的参数中可能会导致严重的安全风险。 - Conorrequire "uri"
download = URI.open('http://example.com/image.png')
File.write('~/image.png', download)
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"
IO.copy_stream(open('http://example.com/image.png'), 'destination.png')
。 - Jankorequire 'open-uri'
这个库,只需使用其下方的代码即可。 - Mirror318