S3
にあるファイルを一括でダウンロードする機能を作ったときのメモ。
ruby
のZIPファイルを扱う方法は色々あるけど rubyzip
を使ってる人が多い印象。
rubyzip
をインストールする
gem install rubyzip
コントローラー
zip_file_name = "SampleZip-#{Time.now.strftime('%Y%m%d%H%M%S')}.zip"
zip_file = Tempfile.new(zip_file_name)
Zip::OutputStream.open(zip_file.path) do |zip|
@targets.each do |target|
#ファイル名を指定してエントリを作成する
zip.put_next_entry("#{target.filename}.pdf")
#S3にあるファイルのURLにアクセスしてGETしたものをZIPエントリに追加
zip.print Net::HTTP.get URI.parse(target.url)
end
#ZIPファイルをダウンロード
send_file(zip_file.path,{:type => 'application/zip',
:disposition => 'attachment',
:filename => zip_file_name})
#temp fileを削除する
zip_file.close
end
わかりやすいようにエラー処理等は省略しているのでコピペ注意