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

后端 未结 3 1746
野的像风
野的像风 2020-12-29 07:46

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 s

相关标签:
3条回答
  • 2020-12-29 08:10

    using the down gem to avoid the security issues of using open-uri:

    image = Down.download(image_url)
    user.image.attach(io: image, filename: "image.jpg")
    
    0 讨论(0)
  • 2020-12-29 08:12

    The simplest way to do this without having to enter filename explicitly is:

    url = URI.parse("https://your-url.com/abc.mp3")
    filename = File.basename(url.path)
    file = URI.open(url)
    user = User.first
    user.avatar.attach(io: file, filename: filename)
    

    This automatically saves the avatar against that particular user object.

    In case you are using a remote service like S3 the URL can be retrieved by:

    user.avatar.service_url
    
    0 讨论(0)
  • 2020-12-29 08:23

    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
    
    0 讨论(0)
提交回复
热议问题