如何在Ruby中生成密码保护(可选)zip文件?

az31mfrm  于 12个月前  发布在  Ruby
关注(0)|答案(1)|浏览(99)

基本的归档文件创建工作如下(使用rubyzip)

Zip::File.open(zipfile_name, create: true) do |zipfile|
  input_filenames.each do |filename|
    zipfile.add(filename, File.join(folder, filename))
  end
end

好吧,我有一段时间了......但现在我需要创建一个密码保护的zip。为此,文档包括:

enc = Zip::TraditionalEncrypter.new('password')
buffer = Zip::OutputStream.write_buffer(encrypter: enc) do |output|
  output.put_next_entry("my_file.txt")
  output.write my_data
end

我不太明白如何将合并与第一种方法(迭代文件列表)结合起来。
密码也是可选的,在我的情况下-这是一个用户的选择是否存档将密码保护或没有。我想避免在每种情况下使用完全不同的代码。

xdnvmnnf

xdnvmnnf1#

可以看到,默认情况下,编译器为nil
但是如果需要的话,您可以动态地传递它
我建议这样的方法:

require "zip"

def zipfile(filenames:, zip_filename:, password: nil)
  # If password was passed, intitialize encrypter
  encrypter = Zip::TraditionalEncrypter.new(password) if password

  # Create buffer, it is the object like StringIO
  # Pass encrypter there, it will be nil if no password
  buffer = Zip::OutputStream.write_buffer(encrypter: encrypter) do |out|
    Array(filenames).each do |filename|
      # Create file inside zip archive
      out.put_next_entry(File.basename(filename))
      # And fill with file content
      out.write File.read(filename)
    end
  end

  # Write result to the zip file
  File.open(zip_filename, "w") { |zipfile| zipfile.write(buffer.string) }
end

当然,您可以修改它或创建单独的实体为您的需要
现在你可以调用这个方法,传递字符串或文件名数组,传递/不传递密码

zipfile(filenames: ["1.txt", "2.txt"], zip_filename: "new.zip", password: "123456")
zipfile(filenames: "/Users/abc/111.txt", zip_filename: "/Users/abc/111.zip")

正如我所看到的,这是rubyzip 3.0的新特性,你需要指定这个版本(例如在Gemfile中)

# Gemfile
source "https://rubygems.org"

gem "rubyzip", "3.0.0.alpha"

并在该版本的上下文中运行脚本

bundle exec ruby zipper.rb

相关问题