How to unzip a file in Ruby on Rails?

后端 未结 4 1678
盖世英雄少女心
盖世英雄少女心 2020-12-08 06:37

I\'m uploading a file to the server in Ruby on Rails

Normally, it\'s a text file and I save it in the model as a \'file\' field in a Submission ActiveRecord with oth

相关标签:
4条回答
  • 2020-12-08 06:53

    Extract Zip files in Ruby

    Once you've installed the rubyzip gem, 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:

    extract_zip(zip_path, extract_destination)
    
    0 讨论(0)
  • 2020-12-08 06:59

    Worked for me:

    gem install rubyzip
    

    main.rb

    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)
          FileUtils.mkdir_p(File.dirname(fpath))
          zip_file.extract(f, fpath) unless File.exist?(fpath)
        end
      end
    end
    
    extract_zip('file.zip', 'tmp')
    
    0 讨论(0)
  • 2020-12-08 07:00

    From the RubyZip project page:

    Rubyzip interface changed!!! No need to do require "zip/zip" and Zip prefix in class names removed.

    So, the example code from @ben-lee should be updated to something like this:

    require 'zip'
    
    Zip::File.open("my.zip") do |zipfile|
      zipfile.each do |file|
        # do something with file
      end
    end
    
    0 讨论(0)
  • 2020-12-08 07:09

    I'd use the rubyzip gem. Specifically this part: https://github.com/rubyzip/rubyzip/blob/master/lib/zip/filesystem.rb

    It creates an artificial file system in memory mirroring the contents of the zip file. Here's an example based of the example from the docs:

    Rubyzip interface changed!!! No need to do require "zip/zip" and Zip prefix in class names removed.

    require 'zip'
    
    Zip::File.open("my.zip") do |zipfile|
      zipfile.each do |file|
        # do something with file
      end
    end
    

    In your case, just put the name of the uploaded tempfile where my.zip is in the example, and you can loop through the contents and do your regular operations on them.

    0 讨论(0)
提交回复
热议问题