如何在不使用 Ruby 保存到磁盘的情况下生成 zip 文件? [英] How can I generate zip file without saving to the disk with Ruby?
问题描述
我在内存中生成了许多 PDF 文件,我想在将它们作为电子邮件附件发送之前将它们压缩成一个 zip 文件.我看过 Rubyzip,它不允许我在不将其保存到磁盘的情况下创建 zip 文件(也许我错了).
I have generated many PDF files in memory and I want to compress them into one zip file before sending it as a email attachment. I have looked at Rubyzip and it does not allows me to create a zip file without saving it to disk (maybe I am wrong).
有什么办法可以在不创建临时文件的情况下压缩这些文件吗?
Is there any way I can compress those file without creating a temp file?
推荐答案
我有一个类似的问题,我使用 rubyzip gem 和 stringio 对象解决了这个问题.事实证明,rubyzip 提供了一个返回 stringio 对象的方法:ZipOutputStream.write_buffer
.
I had a similar problem which I solved using the rubyzip gem and the stringio object.
It turns out that rubyzip provides a method that returns a stringio object: ZipOutputStream.write_buffer
.
您可以使用 put_next_entry
创建您喜欢的 zip 文件结构并写入,完成后您可以倒回 stringio 并使用 sysread 读取二进制数据.
You can create the zip file structure as you like using put_next_entry
and write and once you are finished you can rewind the stringio and read the binary data using sysread.
参见下面的简单示例(适用于 rubyzip 0.9.X)
See the following simple example (works for rubyzip 0.9.X)
require 'zip/zip'
stringio = Zip::OutputStream.write_buffer do |zio|
zio.put_next_entry("test.txt")
zio.write "Hello world!"
end
stringio.rewind
binary_data = stringio.sysread
在 jruby 1.6.5.1 (ruby-1.9.2-p136) (2011-12-27 1bf37c2) (Java HotSpot(TM) 64-Bit Server VM 1.6.0_29) [Windows Server 2008-amd64-java] 上测试)
Tested on jruby 1.6.5.1 (ruby-1.9.2-p136) (2011-12-27 1bf37c2) (Java HotSpot(TM) 64-Bit Server VM 1.6.0_29) [Windows Server 2008-amd64-java])
以下示例适用于 rubyzip >= 1.0.0
The following example works for rubyzip >= 1.0.0
require 'rubygems'
require 'zip'
stringio = Zip::OutputStream.write_buffer do |zio|
zio.put_next_entry("test.txt")
zio.write "Hello world!"
end
binary_data = stringio.string
在 jruby 1.7.22 (1.9.3p551) 2015-08-20 c28f492 上在 OpenJDK 64 位服务器 VM 1.7.0_79-b14 +jit [linux-amd64] 和 rubyzip gem 1.1.7 上测试
Tested on jruby 1.7.22 (1.9.3p551) 2015-08-20 c28f492 on OpenJDK 64-Bit Server VM 1.7.0_79-b14 +jit [linux-amd64] and rubyzip gem 1.1.7
这篇关于如何在不使用 Ruby 保存到磁盘的情况下生成 zip 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!