Rails and RubyZip – Create zip file and delete it after download using send_data

We are not using send_file method because it will get deleted before rails actually starts sending it

 

filename = “#{Rails.root}/public/invoices.zip”
temp_file = Tempfile.new(filename)
input_filenames = Dir.entries(“#{Rails.root}/public/Invoices_pdfs”).select {|f| !File.directory? f}
folder = “#{Rails.root}/public/Invoices_pdfs”

begin
#This is the tricky part
#Initialize the temp file as a zip file
Zip::OutputStream.open(temp_file) { |zos| }

#Add files to the zip file as usual
Zip::File.open(temp_file.path, Zip::File::CREATE) do |zipfile|
input_filenames.each do |file|
zipfile.add(file,  File.join(folder, file))
end
end

#Read the binary data from the file
zip_data = File.read(temp_file.path)

#Send the data to the browser as an attachment
#We do not send the file directly because it will
#get deleted before rails actually starts sending it
send_data(zip_data, :type => ‘application/zip’, :filename => “#{Time.now.to_date}”)
ensure
#Close and delete the temp file
temp_file.close
temp_file.unlink
FileUtils.rm_rf(Dir.glob(“#{Rails.root}/public/Invoices_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