简体   繁体   English

如何使用rubyzip库获取压缩文件的内容?

[英]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. 我正在尝试提取上传的zip文件并将其内容存储在数据库中,每个文件一个条目。 The rubyzip library has nearly no useful documentation. rubyzip库几乎没有有用的文档。

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: 我正在使用rubyzip库,并且已经做到了这一点:

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? 如何设置ZipEntry中的数据? Do I have to use a temp file? 我必须使用临时文件吗?

找到一种更简单的方法:

asset.data = entry.get_input_stream.read

It would seem that you can either use the read_local_entry method like this: 您似乎可以像这样使用read_local_entry方法:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM