ファイルのダウンロード
Railsでファイルのダウンロードを作ってみよう。
前回の続きで、モデルdocumentを作成する。項目はファイル名(filename:string)。
NetBeansだと、プロジェクトの「生成...」からmodelを選択して、引数に
document filename:string
を入力する。
データベースのマイグレーションも「現在のバージョンへ」を選択し作成。
ビューはこんな感じで(index.html.rb)。
<table> <tr> <th>ファイル名</th> </tr> <% @documents.each do |document| %> <tr> <td><%= link_to( h(document.filename), {:controller=>"document",:action=>"download",:id=>document.id } )%> </td> </tr> <% end %> </table>
ローカルホストの/document/indexを参照するとファイル名の一覧が表示される。
ダウンロードするメソッド「download」をコントローラに追加する。
def download document = Document.find(params[:id]) path = "/files/" + document.filename send_file(path) end
テーブルdocumentのfilenameにファイル名を入れ、filesフォルダ下に実際のファイルを保存する。
一覧にはテーブルのfilenameを表示し、ダウンロードの時にfilesフォルダ下のファイルを送る仕組みだ。
これでファイルのダウンロードはできたぞ。