简体   繁体   English

使用rubyzip下载并解压缩远程zip文件

[英]download and extract remote zip file using rubyzip

I am trying to download a zip file, extract the zip and read the files. 我想下载一个zip文件,解压缩并读取文件。 Below is my code snippet: 以下是我的代码片段:

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

When I run this script, I see below error: 当我运行此脚本时,我看到以下错误:

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

I am not able to understand what this error is for ? 我无法理解这个错误是什么? I can download and view the zip from the zip file url. 我可以从zip文件URL下载并查看zip。

Couldn't get the download to work with Restclient so I used net/http instead, tested and works. 无法下载使用Restclient所以我使用net / http代替,测试和工作。 Working with tempfiles and Zip gave me trouble in the past so I rather use a normal file. 使用tempfiles和Zip过去给我带来了麻烦所以我宁愿使用普通文件。 You can delete it afterwards. 您可以在之后删除它。

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

I suspect you have a corrupted zip. 我怀疑你有一个损坏的拉链。 Unzip cannot find the line of code that mark the end of the archive, so either: 解压缩无法找到标记归档结尾的代码行,因此:

  • The archive is corrupt. 存档已损坏。
  • It is not a .zip archive. 它不是.zip存档。
  • There are more than one parts to the archive. 存档有多个部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM