This question already has an answer here:
这个问题在这里已有答案:
- How to unzip a file in Ruby on Rails? 3 answers
- 如何在Ruby on Rails中解压缩文件? 3个答案
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)
#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)