ruby-on-rails - 如何使用 Rails 主动存储从 url 保存图像?

标签 ruby-on-rails rails-activestorage

我正在寻找使用 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

在此先感谢您的任何建议。

最佳答案

就像评论里说的,使用openURI.open非常危险,因为它不仅可以访问文件,还可以通过前缀管道符号来处理调用(例如 open("| ls") )。

Kernel#open and URI.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 of Kernel#open and URI.open. It would be better to use File.open, IO.popen or URI.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/

相关文章:

ruby-on-rails - 在 Ruby on Rails 部分中渲染 React 组件

ruby-on-rails - Rails 服务器不通过命令 "Rails s"启动

ruby-on-rails - 已连接 ActiveStorage : checking if .?对于预加载附件的集合(同时避免对 Attached? 方法进行 n+1 次查询)

ruby-on-rails - 如何在 ActiveStorage Rails 5.2 实现中检索源文件名?

ruby-on-rails - 在rails中,如何将记录作为csv文件返回

ruby-on-rails - 使用 fields_for 的 Rails 错误消息

ruby-on-rails - Rails - 在对 OpenLDAP 服务器进行身份验证后确定组成员身份

ruby-on-rails - 为什么当对象不为零时,事件存储会抛出此错误 : undefined method `upload' for nil:NilClass,

ruby-on-rails - 使用 Active Storage 验证直接上传的文件类型?是否可以?

ruby-on-rails - Rails 5.2 事件存储无法自动加载常量 ActiveStorage::Blob::Analyzable