一時ファイルとしてダウンロードしたファイルをブラウザに送信した後に削除がしたかった時のメモ
結論:send_fileでなくsend_dataを使うと削除できました
ルーティングの設定
routes.rb
resources :hoges do get "download", on: :member end
または
get 'hoges/download' => 'hoges#download'
view側ボタン
<%= button_to "ダウンロード", {controller: 'hoges', action: 'download'}, {method: :get} %>
失敗例:controller側(send_fileの場合)
class HogeController < ApplicationController def download file_name = "file_name_#{params[:id]}.mp3" tmp_file_path = "tmp/" + file_name File.new(tmp_file_path, 'w') // 一時ファイル作成 send_file tmp_file_path File.delete tmp_file_path // ここでエラーになる end end
成功例:controller側(send_dataの場合)
class HogeController < ApplicationController def download file_name = "file_name_#{params[:id]}.mp3" tmp_file_path = "tmp/" + file_name File.new(tmp_file_path, 'w') // 一時ファイル作成 send_data(File.read(tmp_file_path), :filename => file_name) File.delete tmp_file_path end end