Tintin81
Tintin81

Reputation: 10207

How to add existing file to ZIP file using RubyZIP?

In my Rails 4.2 application I am using RubyZIP to create a controller action similar to the following:

class SomeController < ApplicationController

  def some_action
    file_stream = Zip::ZipOutputStream.write_buffer do |zip|
      zip.put_next_entry "dir1/hello.txt"
      zip.print "Hello"
      zip.put_next_entry "dir2/hello.txt"
      zip.print "World"
    end
    file_stream.rewind
    respond_to do |format|
      format.zip do
        send_data file_stream.read, filename: "zip_file.zip"
      end
    end
  end

end

In the example two files are dynamically created and written to, then saved into a ZIP file.

But how can I add a file that already exists (!) to the ZIP file as well, e.g. a PDF file from my /app/assets/documents folder?

This should be much easier to achieve but I can't find any documentation on it.

Thanks for any help.

Upvotes: 2

Views: 6482

Answers (1)

Lavika
Lavika

Reputation: 530

zip_file = File.new(zip_file_path, 'w')

Zip::File.open(zip_file.path, Zip::File::Create) do |zip|
  zip.add(file_name, file_path)
end

zip_file

Here, file_name and file_path are name and paths of the file you want to add to your zip file and zip_file_path is the path of ZipFile. Hope that helps!

Upvotes: 4

Related Questions