2015-10-20 194 views
1

我想下载一个zip文件,解压zip并读取这些文件。下面是我的代码片段:下载并使用rubyzip解压缩远程zip文件

url = "http://localhost/my.zip" 
response = RestClient::Request.execute({:url => url, :method => :get, :content_type => 'application/zip'}) 
zipfile = Tempfile.new("downloaded") 
zipfile.binmode #someone suggested to use binary for tempfile 
zipfile.write(response) 
Zip::ZipFile.open(zipfile.path) do |file| 
    file.each do |content| 
    data = file.read(content) 
end 
end 

当我运行此脚本,我看到下面的错误:

zip_central_directory.rb:97:in `get_e_o_c_d': Zip end of central directory signature not found (Zip::ZipError) 

我不能够理解这个错误是什么?我可以从zip文件网址下载并查看该zip文件。

回答

0

我怀疑你有一个损坏的zip。 解压缩无法找到标记存档末尾的代码行,因此:

  • 存档已损坏。
  • 这不是一个.zip压缩文件。
  • 档案中有多个部分。
+0

是的,可能是压缩文件已损坏。当我访问其他一些远程zip文件时,我的代码可以正常工作。谢谢。 –

0

无法获得下载与Restclient一起使用,所以我用net/http代替,测试和工作。使用tempfiles和Zip在过去给我带来了麻烦,所以我宁愿使用普通文件。您可以在之后删除它。

require 'net/http' 
require 'uri' 
require 'zip/zip' 

url = "http://localhost/my.zip" 
uri = URI.parse(url) 
req = Net::HTTP::Get.new(uri.path) 
filename = './test.zip' 

# download the zip 
File.open(filename,"wb") do |file| 
    Net::HTTP::Proxy(proxy_host, proxy_port, proxy_user, proxy_pass).start(uri.host, uri.port) do |http| 
    http.get(uri.path) do |str| 
     file.write str 
    end 
    end 
end 

# and show it's contents 
Zip::ZipFile.open(filename) do |zip| 
    # zip.each { |entry| p entry.get_input_stream.read } # show contents 
    zip.each { |entry| p entry.name } # show the name of the files inside 
end 
+0

我的代码工作正常(与RestClient)。可能的话,邮编已损坏。代码工作得很好,当我访问一些其他的远程压缩。尽管感谢其他解决方案。 –

相关问题