Ruby:下载zip文件并解压缩
我有一个ruby脚本,它使用rubysRuby:下载zip文件并解压缩,ruby,zip,rubyzip,Ruby,Zip,Rubyzip,我有一个ruby脚本,它使用rubysopen命令从服务器下载远程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
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
stream = open("http://localhost:3000/foobar.zip").read # this outputs the zip content from above
zip = Zip::ZipInputStream.new stream
我尝试使用Rubyzip gem()及其类Zip::ZipInputStream
,如下所示:
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
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
我的问题是:
我自己找到了解决方案,然后在stackoverflow:D()
open
命令(require'openuri'
)StringIO.new(输入)
io迭代ZIP存档中的每个条目。获取下一个条目(它返回一个条目的实例)
io.read
可以获得内容,使用entry.name
可以获得文件名Zip::File.open\u 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
我在上面尝试了同样的代码,但对我无效,我看到了这个错误:
rubyzip-0.9.9/lib/zip/zip\u输入流。rb:52:in
initialize':无法将StringIO转换为String(TypeError)`我正在使用rubyzip
1.1.7,所以可能是问题所在?你从上面复制并粘贴了我的代码吗?在哪一行(你的代码中)错误发生了吗?是的,原来我访问的远程zip已损坏。现在一切正常。谢谢。