簡體   English   中英

從字符串中解壓縮zip存檔

[英]unzipping a zip archive from a string

我有一個字符串的zip存檔,但rubyzip gem似乎想要從文件輸入。 我提出的最好的方法是將zip存檔寫入tempfile,其唯一目的是將文件名傳遞給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

參見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

@ 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

在這種情況下,Ruby的StringIO會有所幫助。

可以把它想象成一個字符串/緩沖區,你可以像處理內存文件一樣對待它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM