How to save an image from a url with rails active storage?

假如想象 提交于 2019-12-04 12:14:20

问题


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

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.

Example: URL of an image 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.


回答1:


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


来源:https://stackoverflow.com/questions/51027995/how-to-save-an-image-from-a-url-with-rails-active-storage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!