Wednesday, February 29, 2012

Using rubyzip in Rails 3

While downloading large files its better to zip it at the server end so that the download becomes much faster.

There is a gem called rubyzip to perform this action.

Add this in your Gemfile

gem "rubyzip", :require => 'zip/zip'

run bundle install

Suppose i have a "folder" which 'has_many' files. So when i try to download the folder, the entire files linked to folder must be downloaded as a zip file. In Folders controller

def download_folder
  @folder = Folder.find(params[:id])
  temp = Tempfile.new("zip-file-#{Time.now}")
  Zip::ZipOutputStream.open(temp.path) do |z|
    @folder.libraries.each do |file|
      z.put_next_entry(file.uploaded_file_file_name)
      z.print IO.read(file.uploaded_file.path)
    end
  end
  send_file temp.path, :type => 'application/zip', :disposition => 'attachment', :filename => "#{@folder.name}.zip"
  temp.delete() #To remove the tempfile
end


Thats it!!!...

3 comments:

  1. not sure, i haven't tried yet. Will try and let you know....

    ReplyDelete
  2. typo:

    send_file t.path .....

    must be:
    send_file temp.path ....



    Thanks for the code!!!

    ReplyDelete
    Replies
    1. oops... thanks for pointing it out, will fix right away.

      Delete