How to upload remote file from url with ActiveStorage Rails
Today I've Learned postclass Medium < ActiveRecord::Base
has_one_attached :image
end
Attach remote file
with ‘require open-uri’
require 'open-uri'
file = open('https://eq8.eu/some-image.jpg')
medium = Medium.last
medium.image.attach(io: file, filename: 'some-image.jpg')
# or
medium.image.attach(io: file, filename: 'some-image.jpg', content_type: 'image/jpg')
Or without require
require 'uri'
file = URI.open('https://eq8.eu/some-image.jpg')
medium = Medium.last
medium.image.attach(io: file, filename: 'some-image.jpg')
# or
medium.image.attach(io: file, filename: 'some-image.jpg', content_type: 'image/jpg')
Attach local file
medium = Medium.last
medium.image.attach(io: File.open("/tmp/some-image.jpg"), filename: "some-image.jpg", content_type: "image/jpg")
Entire blog website and all the articles can be forked from this Github Repo