Wednesday, March 16, 2011

Zip multiple files and download as attachment using rubyzip gem.

rubyzip is a lib for creating / working with zip archives in ruby.

» gem install rubyzip


Sample code

require 'zip/zip'
require 'zip/zipfilesystem'


def download_all
attachments = Upload.find(:all, :conditions => ["source_id = ?", params[:id]])

zip_file_path = "#{RAILS_ROOT}/uploads/download_all.zip"


# see if the file exists already, and if it does, delete it.
if File.file?(zip_file_path)
File.delete(zip_file_path)
end


# open or create the zip file
Zip::ZipFile.open(zip_file_path, Zip::ZipFile::CREATE) { |zipfile|

attachments.each do |attachment|
#document_file_name shd contain filename with extension(.jpg, .csv etc) and url is the path of the document.
zipfile.add( attachment.document_file_name, attachment.document.url)

end

}
#send the file as an attachment to the user.
send_file zip_file_path, :type => 'application/zip', :disposition => 'attachment', :filename => "download_all.zip"

end