3

I am trying to download a zip file, extract the zip and read the files. 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.

SOF User
  • 51
  • 3

2 Answers2

2

Couldn't get the download to work with Restclient so I used net/http instead, tested and works. Working with tempfiles and Zip gave me trouble in the past so I rather use a normal file. 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
peter
  • 41,770
  • 5
  • 64
  • 108
  • My code works fine (with RestClient). Possibly, the zip is corrupted. Code works just fine when I access some other remote zip. Thanks for other solution though. – SOF User Oct 23 '15 at 04:52
1

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.
  • There are more than one parts to the archive.
Andrea Salicetti
  • 2,423
  • 24
  • 37
  • Yes, Possibly, the zip is corrupted. My code works as expected when I access some other remote zip. Thanks. – SOF User Oct 23 '15 at 04:51