1
0

ActiveStorageでBlobをアップロードする

Posted at

前提

  1. AWS ECS Fargate等の使用で、コンテナ内にファイル生成ができない環境を使用している
  2. ActionDispatch::Http::UploadedFile オブジェクトではない方法でファイルを受信している

方法

以下はBase64形式でPNG画像を受信した時、一時ファイルを生成せずにActiveStorageでアップロードする方法です。

image = "data:image/png;base64,xxxxx"
mime_type = image[%r/(image\/[a-z]{3,4})|(application\/[a-z]{3,4})/]
extension = mime_type[%r{\b(?!.*/).*}]
contents = image.sub(%r/data:((image|application)\/.{3,}),/, '')
decoded_data = Base64.decode64(contents)
blob = ActiveStorage::Blob.new(key: ActiveStorage::Blob.generate_unique_secure_token, filename: "image.#{extension}", content_type: mime_type)
blob.upload(StringIO.new(decoded_data, "rb"))

# ActiveRecord に ActiveStorage Objectをアタッチする場合は以下も記載
# ここでは Model を model, ActiveStorage をアタッチするカラムを image とする
# model.image.attach(blob)
1
0
0

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