LoginSignup
2
1

More than 3 years have passed since last update.

ActiveStorageでアップロードした画像を自前で表示するURLを用意する

Posted at

やりたかったこと

WYSIWYなどのエディターで、画像URLを含むHTMLをそのままDBへ保存してrawで表示したかった。

問題

直接service_urlを保存した場合に、アクセストークンが有効期限切れになってしまい、以下のようなエラーが吐かれる。

https://storage.googleapis.com/xxx/6qk30zadasnfkansfalksj34gq?GoogleAccessId=...

<Error>
  <Code>ExpiredToken</Code>
  <Message>The provided token has expired.</Message>
  <Details>Request signature expired at: 2020-09-30T19:07:20+00:00</Details>
</Error>

スクリーンショット 2020-10-05 2.29.58.png

生成用のURLを用意する

アクセストークン付きのservice_urlを生成して表示するURLを用意するため、アセット用のモデルを作成。

asset.rb
class Asset < ApplicationRecord
  has_one_attached :image
end

controllerのshowで画像データを送信するように変更。

assets_controller.rb
class AssetsController < ActionController::Base
  # GET /assets:id
  def show
    asset = Asset.find(params[:id])
    send_data asset.image.download, filename: asset.image.filename.to_s, content_type: asset.image.content_type
  end
end

以下のようなURLをDBに保存することで、アプリケーションのサーバーを経由し、有効期限が切れないで画像を表示することができた。

...
<img src="http://localhost:3000/assets/2" alt="Image">
...
2
1
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
2
1