1
0

More than 3 years have passed since last update.

Rails + heroku + CloudinaryでのURLからの画像保存方法

Last updated at Posted at 2021-08-20

前提条件

rubyとrailsのバージョンは以下の通り。
ruby:2.6.3p62
rails:6.1.3.2

herokuにcloudinaryを追加

herokuのweb画面からcloudinaryを追加する
スクリーンショット 2021-08-20 12.08.30.png

料金プランは無料プランにしている
スクリーンショット 2021-08-20 12.10.52.png

cloudinary.ymlの追加

cloudinaryの画面でYMLリンクをクリックしてymlをダウンロードする。(YMLリンク小さすぎ)
ここにapikeyとか全部書かれている。

スクリーンショット 2021-08-20 12.13.21.png

ダウンロードしたymlはapp/configの下に配置する

gemの追加

Gemfileに以下を追加

gem 'carrierwave'
gem 'cloudinary'

uploderの生成と編集

以下のコマンドでapp/uploaders/cloudinary_image_uploader.rbが生成される

bundle exec rails g uploader CloudinaryImage

cloudinary_image_uploader.rbに以下を追加

include Cloudinary::CarrierWave

以下がcloudinary_image_uploader.rbにあるとcloudinaryに保存されないのでコメントアウト

storage :file

画像の保存

今回はURLからjpeg画像を取得してcloudinaryに保存する

temp_file = Tempfile.new('temp_')
temp_file.binmode
open('画像のURL') do |file|
  temp_file.write(file.read)
end
temp_file.rewind

model.image = ActionDispatch::Http::UploadedFile.new(filename: "ファイル名", type: 'image/jpeg', tempfile: temp_file.open)
model.save!

temp_file.close

参考

1
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0