6
8

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 2018-03-14

Railsチュートリアルでは、画像ファイルの登録までだが、画像ファイルのダウンロード処理まで一貫して書いてみる。

ref: https://github.com/carrierwaveuploader/carrierwave

$ bin/rails -v
Rails 5.1.2

carrierwaveを使用する

gem 'carrierwave'
routes.rb
  resources :pictures, only: [:create] do
    member do
      get :download
    end
  end
picture_uploader.rb
class PictureUploader < CarrierWave::Uploader::Base
  include CarrierWave::MiniMagick
  process resize_to_limit: [128, 128]

  storage :file

  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

  def extension_whitelist
    %w(jpg jpeg gif png)
  end

end
index.html.erb
  <%= form_for(@picture) do |f| %>
      <label>ファイル</label>
      <%= f.file_field :name %>

      <%= submit_tag '送信' %>
  <% end %>
pictures_controller.rb
  def create
    picture = SlackPicture.new(fileupload_param)
    if picture.save
      @picture = picture
    end
    
    render :template => "pictures/index"
  end

ここまでが画像登録、pictureカラムに画像オブジェクトが入っている。実際はpublic/uploads/picture/picture/:id/アップしたファイル名に画像ファイルがある。128x128でリサイズしてある。

index.html.erb
  <% if @picture %>
      <%= image_tag @picture.picture.url %>
      <%= link_to "ダウンロード", download_picture_path(@picture) %>
  <% end %>
pictures_controller.rb
  def download
    @picture = Picture.find(params[:id])
    # ref: https://github.com/carrierwaveuploader/carrierwave#activerecord
    filepath = @picture.picture.current_path
    stat = File::stat(filepath)
    send_file(filepath, :filename => @picture.picture_identifier, :length => stat.size)
  end

ファイルを出力するときは、send_fileメソッドを使う。これで、フォームより画像ファイルをダウンロード可能。

carrierwaveのメソッドは、ここを参照
https://github.com/carrierwaveuploader/carrierwave#activerecord

6
8
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
6
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?