Ruby on Railsダウンロードファイルsend_file、send_data



Ruby Rails Download File Send_file



動作環境、Mac、ubuntu

レール4.2.1



昨日はRailsファイルのアップロード、今日のファイルのダウンロードがありましたが、それほど簡単なことは期待していませんでした

1.ダウンロードページのリンクを追加します



def file_download resource = Resource.find(params[:format]) send_file '# {Rails.root} / public # {resource [: file_path]}' path to the downloaded file // end

2.のコントローラー

get '/admin/file_download'

3.routes.rbを入力してルートを追加します

send_file(path, :filename => 'yourfilename')

了解しました。簡単なことはありません



4.ダウンロードするファイルの名前を指定する場合

data = 'My file content' send_data (data,: filename => 'filename.txt') // note this time: filename should not be spared, there would download things back open

次に、send_dataの使用を見てください

data = 'My file content' file = 'filename.txt' File.open(file, 'w') send_data(data)

さらに、あなたはすることができます

= Link_to 'download', admin_file_download_path (resource.id)