views:

693

answers:

2

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?

+2  A: 

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)
Ivan
Thanks. 10 points for effort!
jcoby
+2  A: 

Found an even more simple way:

asset.data = entry.get_input_stream.read
jcoby