2013-02-15 76 views
1

我在一个字符串中有一个zip归档文件,但rubyzip gem似乎想要从一个文件输入。我拿出最好的是写的zip压缩包来传递文件名以Zip::ZipFile.foreach()的唯一目的的临时文件,但这似乎折磨:从一个字符串中解压zip归档文件

require 'zip/zip' 
def unzip(page) 
    "".tap do |str| 
    Tempfile.open("unzip") do |tmpfile| 
     tmpfile.write(page) 
     Zip::ZipFile.foreach(tmpfile.path()) do |zip_entry| 
     zip_entry.get_input_stream {|io| str << io.read} 
     end 
    end 
    end 
end 

有没有简单的方法?请参阅Ruby Unzip String

回答

3

Zip/Ruby Zip::Archive.open_buffer(...)

require 'zipruby' 
Zip::Archive.open_buffer(str) do |archive| 
    archive.each do |entry| 
    entry.name 
    entry.read 
    end 
end 
+0

谢谢 - 这很好用!在http://stackoverflow.com/a/14912237/558639 – 2013-02-16 16:04:36

-1

Ruby的StringIO会在这种情况下帮助。

把它看作一个字符串/缓冲区,你可以像内存文件一样对待。

+0

查看我完整的答案我知道所有关于StringIO的信息。我不认为Zip :: ZipFile可以处理一个StringIO对象,但我很乐意被证明是错误的。 – 2013-02-16 06:17:49

+0

它需要文件名。不是流式物体 – sergeych 2016-02-18 16:51:15

0

@ maerics的回答向我介绍了zipruby gem(不要与rubyzip gem混淆)。它运作良好。我的完整代码如下所示:

require 'zipruby' 

# Given a string in zip format, return a hash where 
# each key is an zip archive entry name and each 
# value is the un-zipped contents of the entry 
def unzip(zipfile) 
    {}.tap do |entries| 
    Zip::Archive.open_buffer(zipfile) do |archive| 
     archive.each do |entry| 
     entries[entry.name] = entry.read 
     end 
    end 
    end 
end