Wednesday 17 October 2012

Zip the files and download all in rails 3

In one of my project client asked me to give download all link for one folder which contains files. For that i have used this method which is using Tempfile to store files temperorily, zip files together using 'rubyzip' gem.

use this in your gem file,

gem 'rubyzip'

run bundle install

#controller

def download_all
      @records = Record.all
      if !@records.blank?
      file_name = 'download_files.zip'
      t = Tempfile.new("temp-filename-#{Time.now}")
      Zip::ZipOutputStream.open(t.path) do |z|
        @records.each do |img|
          file_path = img.image_name.to_s
          z.put_next_entry(file_path)
          z.print IO.read(img.image_name.path)
        end
      end
      send_file t.path, :type => 'application/zip', :x_sendfile=>true,
        :disposition => 'attachment',
        :filename => file_name
      t.close
    end
  end






Thank you guys..

1 comment:

  1. Really Good blog post.provided a helpful information.I hope that you will post more updates like this Ruby on Rails Online Training India

    ReplyDelete