3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rails carrierwaveで画像をダウンロードさせる

Last updated at Posted at 2019-12-16

※carrierwaveでアップロードはできている前提です。

carrierwaveの設定

developmentではapp/public/uploads配下に保存して、
productionではGoogle Cloud Storageに保存します。

fuga_uploader.rb
class FugaUploader < CarrierWave::Uploader::Base
  ...
  # Choose what kind of storage to use for this uploader:
  if Rails.env.production?
    storage :fog
  else
    storage :file
  end
  ...

1. コントローラーに処理追加

app/controllers/hoge_controller.rb
  def download
    hoge = Hoge.find(download_params[:id])
    image = hoge.image # imageはFugaUploaderオブジェクト
    send_data(image.read, filename: "download#{File.extname(image.path)}")
  end
...
  def download_params
    params.permit(:id)
  end

2. viewにリンク設置

ターボリンク使っている場合は、turbolinks: "false"しないとURLが変わっちゃいます。

app/views/hoge/show.html.erb
        <div>
          <%= link_to download_hoge_path(@hoge), data: { turbolinks: "false", confirm: 'ダウンロードしますか?' } do %>
            <%= image_tag @hoge.image.to_s %>
          <% end %>
        </div>

3. ルーティング設定

config/routes.rb
  resources :hoge do
    member do
      get :download
    end
  end
3
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
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?