Ruby:下载zip文件并解压缩

23t*_*tux 6 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
Run Code Online (Sandbox Code Playgroud)

我尝试使用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
Run Code Online (Sandbox Code Playgroud)

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

 Failure/Error: zip = Zip::ZipInputStream.new stream
 ArgumentError:
   string contains null byte
Run Code Online (Sandbox Code Playgroud)

我的问题是:

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

23t*_*tux 7

我自己找到了解决方案然后在stackoverflow:D(如何在Ruby中迭代内存中的zip文件)

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
Run Code Online (Sandbox Code Playgroud)
  1. 下载你的ZIP文件,我正在使用HTTParty(但你也可以使用ruby的open命令(require 'open-uri').
  2. 使用将其转换为StringIOStringIO.new(input)
  3. 使用io.get_next_entry(它返回一个实例Entry)迭代ZIP存档中的每个条目
  4. 随着io.read你获得内容,并entry.name获得文件名.


Pro*_*dis 7

就像我在/sf/answers/3031225571/ 中评论的那样,我们可以使用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
Run Code Online (Sandbox Code Playgroud)