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