Official Rubyzip repository
Rubyzip is a ruby library for reading and writing zip files.
If you think you have found a security issue with this library, please don't submit a public issue or PR. Email me directly at [email protected] with as much information as you can provide - steps for replication are particularly helpful if you can - and we'll get it sorted ASAP. Thank you.
The public API of some classes has been modernized to use named parameters for optional arguments. Please check your usage of the following Rubyzip classes:
FileEntryInputStreamOutputStreamPlease see Updating to version 3.x in the wiki for details.
Version 3.x requires at least Ruby 3.0.
Version 2.x requires at least Ruby 2.4, and is known to work on Ruby 3.x.
It is not recommended to use any versions of Rubyzip earlier than 2.3 due to security issues.
Rubyzip is available on RubyGems:
gem install rubyzipOr in your Gemfile:
gem 'rubyzip', require: 'zip' # For versions before 3.4.
gem 'rubyzip' # For version 3.4 and after.From version 3.4 onwards, you can require either 'zip' or 'rubyzip' to use this library. Before version 3.4 you need to require 'zip' explicitly.
require 'rubygems'
require 'zip'
folder = "Users/me/Desktop/stuff_to_zip"
input_filenames = ['image.jpg', 'description.txt', 'stats.csv']
zipfile_name = "/Users/me/Desktop/archive.zip"
Zip::File.open(zipfile_name, create: true) 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("myFile") { |f| f.write "myFile contains just this" }
endZip::OutputStreamrequire 'rubygems'
require 'zip'
Zip::OutputStream.open('archive.zip') do |zos|
# Quick.
zos.put_next_entry('greeting.txt')
zos << 'Hello, World!'
# More control.
# You MUST NOT make any calls on your `Entry` after calling `put_next_entry`.
entry = Zip::Entry.new(nil, 'parting.txt')
entry.atime = Time.now
zos.put_next_entry(entry)
zos.write('TTFN')
endYou can generate a Zip archive in memory using Zip::OutputStream.write_buffer.
If you wish to suppress extra fields from being added to your entries, you can do so by passing the suppress_extra_fields parameter to any of the archive opening calls within Zip::File or Zip::OutputStream, e.g.:
# Suppress all extra fields.
Zip::File.open('archive.zip', create: true, suppress_extra_fields: true)
Zip::OutputStream.open('archive.zip', suppress_extra_fields: true)
# Suppress an individual extra field.
Zip::File.open('archive.zip', create: true, suppress_extra_fields: :zip64)
Zip::OutputStream.open('archive.zip', suppress_extra_fields: :zip64)
# Suppress multiple extra fields.
Zip::File.open('archive.zip', create: true, suppress_extra_fields: [:ntfs, :zip64])
Zip::OutputStream.open('archive.zip', suppress_extra_fields: [:ntfs, :zip64])Note that there are some extra fields that cannot be suppressed at all (e.g. :aes), and some which will only be suppressed if it is safe to do so (e.g. :zip64).
Zip::File#add_recursive adds the contents of a directory (not the directory itself) to an archive, recursing into subdirectories:
Zip::File.open('archive.zip', create: true) do |zipfile|
zipfile.add_recursive('/path/to/directory')
endPass prefix: (default '') to nest the contents under a prefix inside the archive, and max_depth: (default 16) to limit how many directory levels are walked. Symlinks are always skipped (ignored, with a warning), rather than followed or added.
For more manual control, here is a hand-rolled version of the same thing:
…To save zip archives with their entries sorted by name (see below), set ::Zip.sort_entries to true
Vegetable/
Vegetable/bean
Vegetable/carrot
Vegetable/celery
fruit/
fruit/apple
fruit/kiwi
fruit/mango
fruit/orangeOpening an existing zip file with this option set will not change the order of the entries automatically. Altering the zip file - adding an entry, renaming an entry, adding or changing the archive comment, etc - will cause the ordering to be applied when closing the file.
On Posix file systems the default file permissions applied to a new archive
are (0666 - umask), which mimics the behavior of standard tools such as touch.
On Windows the default file permissions are set to 0644 as suggested by the Ruby File documentation.
When modifying a zip archive the file permissions of the archive are preserved.
MAX_SIZE = 1024**2 # 1MiB (but of course you can increase this)
Zip::File.open('foo.zip') do |zip_file|
# Handle entries one by one
zip_file.each do |entry|
puts "Extracting #{entry.name}"
raise 'File too large when extracted' if entry.size > MAX_SIZE
# Extract to file or directory based on name in the archive
entry.extract
# Read into memory
content = entry.get_input_stream.read
end
# Find specific entry
entry = zip_file.glob('*.csv').first
raise 'File too large when extracted' if entry.size > MAX_SIZE
puts entry.get_input_stream.read
endTo extract every entry in an archive at once, preserving its directory structure, use Zip::File#extract_all:
Zip::File.open('foo.zip') do |zip_file|
zip_file.extract_all('/path/to/destination')
endAs with extract, existing files at the destination will raise Zip::DestinationExistsError unless a block is passed to resolve the conflict (see Existing Files below). Symlink entries are always skipped (ignored, with a warning), rather than extracted.
Zip::InputStreamZip::InputStream can be used for faster reading of zip file content because it does not read the Central directory up front.
There is one exception where it can not work however, and this is if the file does not contain enough information in the local entry headers to extract an entry. This is indicated in an entry by the General Purpose Flag bit 3 being set.
If bit 3 (0x08) of the general-purpose flags field is set, then the CRC-32 and file sizes are not known when the header is written. The fields in the local header are filled with zero, and the CRC-32 and size are appended in a 12-byte structure (optionally preceded by a 4-byte signature) immediately after the compressed data.
If Zip::InputStream finds such an entry in the zip archive it will raise an exception (Zip::StreamingError).
Zip::InputStream is not designed to be used for random access in a zip file. When performing any operations on an entry that you are accessing via Zip::InputStream#get_next_entry then you should complete any such operations before the next call to get_next_entry.
Zip::InputStream.open('file.zip') do |zip_stream|
while entry = zip_stream.get_next_entry
# All required operations on `entry` go here.
end
end # The `InputStream` is closed at the end of the block.Any attempt to move about in a zip file opened with Zip::InputStream could result in the incorrect entry being accessed and/or Zlib buffer errors. If you need random access in a zip file, use Zip::File.
Rubyzip supports reading and writing zip files with AES encryption (reading: version 3.1 and later; writing: version 3.7 and later), and reading and writing zip files with traditional zip encryption (a.k.a. "ZipCrypto"). Encryption is currently only available with the stream API, with either files or buffers, e.g.:
# Writing.
enc = Zip::TraditionalEncrypter.new('password')
buffer = Zip::OutputStream.write_buffer(::StringIO.new(''), enc) do |output|
output.put_next_entry("my_file.txt")
output.write my_data
end
# Reading.
dec = Zip::TraditionalDecrypter.new('password')
Zip::InputStream.open(buffer, 0, dec) do |input|
entry = input.get_next_entry
puts "Contents of '#{entry.name}':"
puts input.read
end…EntryYou can also decrypt an Entry by passing a decrypter into Zip::Entry#get_input_stream. This allows you to decrypt files from a Zip file with different passwords.
Zip::File.open('aes-encrypted-file.zip') do |zip|
entries = [['file1.txt', 'password1'], ['file2.txt', 'password2']]
entries.each do |entry_name, password|
entry = zip.find_entry(entry_name)
dec = Zip::AESDecrypter.new(password, Zip::AESEncryption::STRENGTH_256_BIT)
zis = entry.get_input_stream(decrypter: dec)
puts "Contents of '#{entry.name}':"
puts zis.read
end
endThis is an evolving feature and the interface for encryption may change in future versions.
Use write_buffer instead open. Thanks to @jondruse
buffer = Zip::OutputStream.write_buffer do |out|
@zip_file.entries.each do |e|
unless [DOCUMENT_FILE_PATH, RELS_FILE_PATH].include?(e.name)
out.put_next_entry(e.name)
out.write e.get_input_stream.read
end
end
out.put_next_entry(DOCUMENT_FILE_PATH)
out.write xml_doc.to_xml(:indent => 0).gsub("\n","")
out.put_next_entry(RELS_FILE_PATH)
out.write rels.to_xml(:indent => 0).gsub("\n","")
end
File.open(new_path, "wb") {|f| f.write(buffer.string) }By default, rubyzip will not overwrite files if they already exist inside of the extracted path. To change this behavior, you may specify a configuration option like so:
Zip.on_exists_proc = trueIf you're using rubyzip with rails, consider placing this snippet of code in an initializer file such as config/initializers/rubyzip.rb
Additionally, if you want to configure rubyzip to overwrite existing files while creating a .zip file, you can do so with the following:
Zip.continue_on_exists_proc = trueTo store non-English filenames as UTF-8 (decoded correctly by Windows 7 or later and other modern tools), set this option:
Zip.unicode_names = trueSometimes file names inside zip contain non-ASCII characters. If you can assume which encoding was used for such names and want to be able to find such entries using find_entry then you can force assumed encoding like so:
Zip.force_entry_names_encoding = 'UTF-8'Allowed encoding names are the same as accepted by String#force_encoding
Some zip files might have an invalid date format, which will raise a warning. You can hide this warning with the following setting:
Zip.warn_invalid_date = falseWhen reading a zip file it is potentially dangerous to trust what it tells you about how many entries it contains. A malformed zip file could claim a high number of entries in an attempt to waste internal resources, or crash the processing application.
By default rubyzip will warn if the number of declared entries is impossible based on the actual size of the Central Directory headers. You can set this check to raise an error:
Zip.validate_declared_number_of_entries = trueIt is likely that the default behaviour for this check will be changed to raise an error in version 4.
No open issues yet, or sync has not completed.