Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 475
jcoby Avatar asked Oct 25 '08 18:10

jcoby


2 Answers

Found an even more simple way:

asset.data = entry.get_input_stream.read
like image 129
jcoby Avatar answered Sep 20 '22 23:09

jcoby


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)
like image 42
Ivan Avatar answered Sep 19 '22 23:09

Ivan