如何在rails中解压缩包含文件夹和文件的zip文件,同时保持目录结构[重复]

[英]How to unzip a zip file containing folders and files in rails, while keeping the directory structure [duplicate]


This question already has an answer here:

这个问题在这里已有答案:

I need to extract a zip file that containes many folders and files using rails ziprails gem. While also keeping the files and folders organized the way they where ziped.

我需要使用rails ziprails gem提取包含许多文件夹和文件的zip文件。同时还保持文件和文件夹的组织方式。

This was not as straight forward as i though. Please see the solution i found beneath (added for future reference)

这并不像我那样直截了当。请参阅我在下面找到的解决方案(添加以备将来参考)

2 个解决方案

#1


20  

This worked for me. Gave the same result as you would expect when unziping a ziped folder with subfolders and files.

这对我有用。与子文件夹和文件解压缩ziped文件夹时的结果相同。

Zip::ZipFile.open(file_path) { |zip_file|
     zip_file.each { |f|
     f_path=File.join("destination_path", f.name)
     FileUtils.mkdir_p(File.dirname(f_path))
     zip_file.extract(f, f_path) unless File.exist?(f_path)
   }
  }

Solution from this site: http://bytes.com/topic/ruby/answers/862663-unzipping-file-upload-ruby

该站点的解决方案:http://bytes.com/topic/ruby/answers/862663-unzipping-file-upload-ruby

#2


2  

Extract Zip archives in Ruby

You need the rubyzip gem for this. Once you've installed it, you can use this method to extract zip files:

你需要rubyzip gem。安装后,可以使用此方法提取zip文件:

require 'zip'

def extract_zip(file, destination)
  FileUtils.mkdir_p(destination)

  Zip::File.open(file) do |zip_file|
    zip_file.each do |f|
      fpath = File.join(destination, f.name)
      zip_file.extract(f, fpath) unless File.exist?(fpath)
    end
  end
end

You use it like this:

你这样使用它:

file_path   = "/path/to/my/file.zip"
destination = "/extract/destination/"

extract_zip(file_path, destination)

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2013/11/03/c43975c9bc1ba938d92fc8735c9aac85.html



 
© 2014-2018 ITdaan.com 粤ICP备14056181号