Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 571
Ed_ Avatar asked Jun 25 '18 16:06

Ed_


People also ask

What is Activestorage?

Active Storage facilitates uploading files to a cloud storage service like Amazon S3, Google Cloud Storage, or Microsoft Azure Storage and attaching those files to Active Record objects.


1 Answers

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")"

like image 174
Ed_ Avatar answered Sep 29 '22 16:09

Ed_