Ruby: Download the zip file and extract

I have a ruby ​​script that downloads a remote zip file from the server using the rubys command open. When I look at the downloaded content, it shows something like this:

PK\x03\x04\x14\x00\b\x00\b\x00\x9B\x84PG\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\n\x00\x10\x00foobar.txtUX\f\x00\x86\v!V\x85\v!V\xF6\x01\x14\x00K\xCB\xCFOJ,RH\x03S\\\x00PK\a\b\xC1\xC0\x1F\xE8\f\x00\x00\x00\x0E\x00\x00\x00PK\x01\x02\x15\x03\x14\x00\b\x00\b\x00\x9B\x84PG\xC1\xC0\x1F\xE8\f\x00\x00\x00\x0E\x00\x00\x00\n\x00\f\x00\x00\x00\x00\x00\x00\x00\x00@\xA4\x81\x00\x00\x00\x00foobar.txtUX\b\x00\x86\v!V\x85\v!VPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x00D\x00\x00\x00T\x00\x00\x00\x00\x00

I tried using the Rubyzip gem ( https://github.com/rubyzip/rubyzip ) along with my class Zip::ZipInputStreamas follows:

stream = open("http://localhost:3000/foobar.zip").read # this outputs the zip content from above
zip = Zip::ZipInputStream.new stream

Unfortunately, this causes an error:

 Failure/Error: zip = Zip::ZipInputStream.new stream
 ArgumentError:
   string contains null byte

My questions:

  • Is it even possible to download a ZIP file and extract its contents in memory?
  • Is Rubyzip the right library for this?
  • If so, how can I extract the content?
+4
source share
2 answers

, stackoverflow: D ( zip Ruby)

input = HTTParty.get("http://example.com/somedata.zip").body
Zip::InputStream.open(StringIO.new(input)) do |io|
  while entry = io.get_next_entry
    puts entry.name
    parse_zip_content io.read
  end
end
  • ZIP , HTTParty ( ruby ​​ open (require 'open-uri').
  • StringIO, StringIO.new(input)
  • ZIP- io.get_next_entry ( Entry)
  • io.read , entry.name .
+5

fooobar.com/questions/598491/..., Zip::File.open_buffer:

require 'open-uri'

content = open('http://localhost:3000/foobar.zip')

Zip::File.open_buffer(content) do |zip|
  zip.each do |entry|
    puts entry.name
    # Do whatever you want with the content files.
  end
end
+1

Source: https://habr.com/ru/post/1611959/


All Articles