Help us understand the problem. What is going on with this article?

rubyzipを使ってS3のファイルをZIPダウンロードする

More than 3 years have passed since last update.

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      

わかりやすいようにエラー処理等は省略しているのでコピペ注意

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away