【问题标题】:download and extract remote zip file using rubyzip使用 ruby​​zip 下载并解压远程 zip 文件
【发布时间】:2015-10-20 07:56:02
【问题描述】:

我正在尝试下载一个 zip 文件,解压缩该 zip 文件并读取文件。下面是我的代码 sn-p:

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。

【问题讨论】:

    标签: ruby-on-rails ruby rubyzip


    【解决方案1】:

    无法让下载与 Restclient 一起使用,因此我使用 net/http 代替,经过测试并可以正常工作。过去使用临时文件和 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
    

    【讨论】:

    • 我的代码工作正常(使用 RestClient)。可能是 zip 已损坏。当我访问其他一些远程 zip 时,代码工作得很好。感谢您提供其他解决方案。
    【解决方案2】:

    我怀疑您的 zip 已损坏。 解压找不到标记存档结束的代码行,所以要么:

    • 存档已损坏。
    • 它不是 .zip 存档。
    • 存档不止一个部分。

    【讨论】:

    • 是的,可能是压缩包已损坏。当我访问其他一些远程 zip 时,我的代码按预期工作。谢谢。
    猜你喜欢
    • 2016-01-15
    • 2021-03-07
    • 1970-01-01
    • 2011-05-28
    • 1970-01-01
    • 2021-11-23
    • 1970-01-01
    • 2021-03-03
    • 2023-03-22
    相关资源
    最近更新 更多