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.
This was not as straight forward as i though. Please see the solution i found beneath (added for future reference)
To unzip a single file or folder, open the zipped folder, then drag the file or folder from the zipped folder to a new location.
Here, I have right-clicked on the zipped file and selected "Extract to here." "Extract" is the same thing as "unzip." Windows also sometimes places "Extract files" links in toolbars which may be useful to you. Windows generally opens a wizard to ask where you want the files extracted.
A zip file on your computer takes up less space than the original file, meaning you can store folders as zips and extract them when needed.
This worked for me. Gave the same result as you would expect when unzipping a zipped folder with subfolders and files.
Zip::Zip.open(file_path) do |zip_file|
zip_file.each do |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)
end
end
The solution from this site: http://bytes.com/topic/ruby/answers/862663-unzipping-file-upload-ruby
You need the rubyzip
gem for this. Once you've installed it, you can use this method to extract zip files:
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With