Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

download and extract remote zip file using rubyzip

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.

like image 395
SOF User Avatar asked Mar 10 '26 01:03

SOF User


1 Answers

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
like image 147
peter Avatar answered Mar 12 '26 16:03

peter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!