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

Ruby on rails 使用rubyzip下载并解压缩远程zip文件,ruby-on-rails,ruby,rubyzip,Ruby On Rails,Ruby,Rubyzip,我正在尝试下载一个zip文件,解压缩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 su

我正在尝试下载一个zip文件,解压缩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)

我无法理解这个错误的原因是什么?我可以从压缩文件url下载并查看压缩文件。

我怀疑您的压缩文件已损坏。 解压找不到标记存档结束的代码行,因此:

  • 档案已损坏
  • 它不是.zip存档
  • 存档中有多个部分

无法使下载与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

是的,可能是拉链坏了。当我访问其他远程zip时,我的代码按预期工作。谢谢。我的代码(与RestClient一起)运行良好。可能是拉链坏了。当我访问其他远程zip时,代码工作正常。谢谢你的其他解决方案。