如何使用 Rails 活动存储从 url 保存图像? [英] How to save an image from a url with rails active storage?

查看:22
本文介绍了如何使用 Rails 活动存储从 url 保存图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望使用 rails 5.2 主动存储保存位于另一个 http Web 服务器上的文件(在本例中为图像).

I'm looking to save a file (in this case an image) located on another http web server using rails 5.2 active storage.

我有一个带有源 url 字符串参数的对象.然后在 before_save 上,我想抓取远程图像并保存.

I have an object with a string parameter for source url. Then on a before_save I want to grab the remote image and save it.

示例:图片的网址 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

预先感谢您的任何建议.

Thanks in advance for any suggestions.

推荐答案

刚刚找到我自己问题的答案.我的第一直觉非常接近......

Just found the answer to my own question. My first instinct was pretty close...

require 'open-uri'

class User < ApplicationRecord
  has_one_attached :avatar
  before_save :grab_image

  def grab_image
    downloaded_image = open("http://www.example.com/image.jpg")
    self.avatar.attach(io: downloaded_image  , filename: "foo.jpg")
  end

end

更新:请注意下面的评论,您必须小心不要将用户输入传递给打开,它可以执行任意代码,例如打开(|日期")

Update: please note comment below, "you have to be careful not to pass user input to open, it can execute arbitrary code, e.g. open("|date")"

这篇关于如何使用 Rails 活动存储从 url 保存图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆