Rails and RubyZip – Create zip file and download using send_file

def make_zip

# Path where your pdfs are situated (‘my_pdf’ is folder with pdfs)
folder = “#{Rails.root}/public/my_pdfs”
input_filenames = Dir.entries(“#{Rails.root}/public/my_pdfs”).select {|f| !File.directory? f}

zipfile_name = “#{Rails.root}/public/myfirstzipfile.zip”

Zip::File.open(zipfile_name, Zip::File::CREATE) do |zipfile|
input_filenames.each do |filename|
# Two arguments:
# – The name of the file as it will appear in the archive
# – The original file, including the path to find it
zipfile.add(filename,  File.join(folder, filename))
end
zipfile.get_output_stream(“success”) { |os| os.write “All done successfully” }
end
send_file(File.join(“#{Rails.root}/public/”, ‘myfirstzipfile.zip’), :type => ‘application/zip’, :filename => “#{Time.now.to_date}.zip”)
# Remove content from ‘my_pdfs’ folder if you want
FileUtils.rm_rf(Dir.glob(“#{Rails.root}/public/my_pdfs/*”))

end

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s