从字符串中解压缩zip存档

时间:2013-02-15 07:12:59

标签: ruby zip stringio rubyzip

我在字符串中有一个zip存档,但是rubyzip gem似乎想要从文件输入。我提出的最好的方法是将zip存档写入临时文件,其唯一目的是将文件名传递给Zip::ZipFile.foreach(),但这似乎受到折磨:

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 个答案:

答案 0 :(得分:4)

请参阅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

答案 1 :(得分: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

答案 2 :(得分:-1)

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

将其视为字符串/缓冲区,您可以将其视为内存中文件。