Ruby:下载zip文件并解压缩

时间:2015-10-16 14:43:12

标签: ruby zip rubyzip

我有一个ruby脚本,使用rubys open命令从服务器下载远程ZIP文件。当我查看下载的内容时,它会显示如下内容:

PK\x03\x04\x14\x00\b\x00\b\x00\x9B\x84PG\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\n\x00\x10\x00foobar.txtUX\f\x00\x86\v!V\x85\v!V\xF6\x01\x14\x00K\xCB\xCFOJ,RH\x03S\\\x00PK\a\b\xC1\xC0\x1F\xE8\f\x00\x00\x00\x0E\x00\x00\x00PK\x01\x02\x15\x03\x14\x00\b\x00\b\x00\x9B\x84PG\xC1\xC0\x1F\xE8\f\x00\x00\x00\x0E\x00\x00\x00\n\x00\f\x00\x00\x00\x00\x00\x00\x00\x00@\xA4\x81\x00\x00\x00\x00foobar.txtUX\b\x00\x86\v!V\x85\v!VPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x00D\x00\x00\x00T\x00\x00\x00\x00\x00

我尝试使用Rubyzip gem(https://github.com/rubyzip/rubyzip)及其类Zip::ZipInputStream,如下所示:

stream = open("http://localhost:3000/foobar.zip").read # this outputs the zip content from above
zip = Zip::ZipInputStream.new stream

不幸的是,这会引发错误:

 Failure/Error: zip = Zip::ZipInputStream.new stream
 ArgumentError:
   string contains null byte

我的问题是:

  1. 通常,是否可以下载ZIP文件并将其内容提取到内存中?
  2. Rubyzip是否适合它?
  3. 如果是,我该如何提取内容?

2 个答案:

答案 0 :(得分:7)

我自己找到了解决方案,然后在stackoverflow:D(How to iterate through an in-memory zip file in Ruby

input = HTTParty.get("http://example.com/somedata.zip").body
Zip::InputStream.open(StringIO.new(input)) do |io|
  while entry = io.get_next_entry
    puts entry.name
    parse_zip_content io.read
  end
end
  1. 下载您的ZIP文件,我使用HTTParty(但您也可以使用ruby' open命令(require 'open-uri')。
  2. 使用StringIO
  3. 将其转换为StringIO.new(input)信息流
  4. 使用io.get_next_entry遍历ZIP存档中的每个条目(它返回Entry的实例)
  5. 使用io.read获取内容,使用entry.name获取文件名。

答案 1 :(得分:4)

就像我在https://stackoverflow.com/a/43303222/4196440中发表的评论一样,我们可以使用Zip::File.open_buffer

require 'open-uri'

content = open('http://localhost:3000/foobar.zip')

Zip::File.open_buffer(content) do |zip|
  zip.each do |entry|
    puts entry.name
    # Do whatever you want with the content files.
  end
end
相关问题