我正在寻找使用 rails 5.2 active storage 保存位于另一个 http web 服务器上的文件(在本例中为图像)。
我有一个带有源 url 字符串参数的对象。然后在 before_save 上,我想抓取远程图像并保存它。
示例:图片的 URL http://www.example.com/image.jpg .
require 'open-uri'
class User < ApplicationRecord
has_one_attached :avatar
before_save :grab_image
def grab_image
#this indicates what I want to do but doesn't work
downloaded_image = open("http://www.example.com/image.jpg")
self.avatar.attach(downloaded_image)
end
end
在此先感谢您的任何建议。
最佳答案
就像评论里说的,使用open
或 URI.open
非常危险,因为它不仅可以访问文件,还可以通过前缀管道符号来处理调用(例如 open("| ls")
)。
Kernel#open
andURI.open
enable not only file access but also process invocation by prefixing a pipe symbol (e.g.,open("| ls")
). So, it may lead to a serious security risk by using variable input to the argument ofKernel#open
andURI.open
. It would be better to useFile.open
,IO.popen
orURI.parse#open
explicitly.
摘自 Rubocop 文档:https://docs.rubocop.org/rubocop/1.8/cops_security.html#securityopen
因此,更安全的解决方案是:
class User < ApplicationRecord
has_one_attached :avatar
before_save :grab_image
def grab_image
downloaded_image = URI.parse("http://www.example.com/image.jpg").open
avatar.attach(io: downloaded_image, filename: "foo.jpg")
end
end
关于ruby-on-rails - 如何使用 Rails 主动存储从 url 保存图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51027995/