How do I get a zipped file's content using the rubyzip library?
Asked Answered
S

2

7

I'm trying to extract an uploaded zip file and store its contents in the database, one entry per file. The rubyzip library has nearly no useful documentation.

There is an assets table that has key :string (file name) and data :binary (file contents).

I'm using the rubyzip library, and have made it as far as this:

Zip::ZipFile.open(@file_data.local_path) do |zipfile|
  zipfile.each do |entry|
    next if entry.name =~ /__MACOSX/ or entry.name =~ /\.DS_Store/ or !entry.file?

    asset = self.assets.build
    asset.key = entry.name
    asset.data = ??  # what goes here?
  end
end

How can I set the data from a ZipEntry? Do I have to use a temp file?

Sokul answered 25/10, 2008 at 18:28 Comment(0)
S
11

Found an even more simple way:

asset.data = entry.get_input_stream.read
Sokul answered 25/10, 2008 at 18:59 Comment(0)
G
6

It would seem that you can either use the read_local_entry method like this:

asset.data = entry.read_local_entry {|z| z.read }

Or, you could save the entry with this method:

data = entry.extract "#{RAILS_ROOT}/#{entry.name}"
asset.data = File.read("#{RAILS_ROOT}/#{entry.name}")

I'm not sure how those will work, but maybe they'll help you find the right method (if this ain't it).

And, one more alternative:

asset.data = zipfile.file.read(entry.name)
Goshorn answered 25/10, 2008 at 18:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.