Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)

like image 805
Ole Henrik Skogstrøm Avatar asked Nov 03 '13 15:11

Ole Henrik Skogstrøm


People also ask

How do I unzip a folder in a folder?

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.

Is extracting the same as unzipping a file?

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.

Can a zip file contain folders?

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.


2 Answers

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

like image 142
Ole Henrik Skogstrøm Avatar answered Oct 05 '22 03:10

Ole Henrik Skogstrøm


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:

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)
like image 24
Sheharyar Avatar answered Oct 05 '22 04:10

Sheharyar