我想从内存中流式传输数据到tar/gz格式(可以将多个文件流式传输到tar中,但不应该接触硬盘,只进行流式传输!),然后流式传输它们到其他地方(在我的情况下是HTTP请求正文)。
有人知道是否已经存在可以实现此功能的库?Rails中是否有类似的东西?
libarchive-ruby 只是一个C语言包装器,看起来非常依赖于平台(文档要求您在安装步骤中进行编译?!)。
解决方案:
require 'zlib'
require 'rubygems/package'
tar = StringIO.new
Gem::Package::TarWriter.new(tar) { |writer|
writer.add_file("a_file.txt", 0644) { |f|
(1..1000).each { |i|
f.write("some text\n")
}
}
writer.add_file("another_file.txt", 0644) { |f|
f.write("some more text\n")
}
}
tar.seek(0)
gz = Zlib::GzipWriter.new(File.new('this_is_a_tar_gz.tar.gz', 'wb')) # Make sure you use 'wb' for binary write!
gz.write(tar.read)
tar.close
gz.close
就是这样!您可以将GzipWriter中的文件替换为任何IO以保持流式传输。感谢dw11wtq提供的帮助!