我正在尝试下载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文件URL下载并查看zip。
答案 0 :(得分:1)
无法让下载与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
答案 1 :(得分:0)
我怀疑你的拉链已损坏了。 解压缩无法找到标记归档结尾的代码行,因此: