rails导出zip文件的策略

在实际项目开发中需要将文件打包下载,由于是在window下开发,故在本地环境中和线上环境中的处理略有不同

不多说,上代码:

# window下利用zipfile生成zip文件
def self.zip_file_development(files)
    tmp_file_path = "#{Rails.root}/zip_file"
    date = "#{Time.now.strftime('%Y%m%d')}"
    rand_name = SecureRandom.hex
    path = File.join(tmp_file_path, date)
    FileUtils.mkdir_p(path) unless File.exist?(path)
    file_path = File.join(tmp_file_path,date, rand_name)
    if File.file?(file_path)
      File.delete(file_path)
    end
    file_path = "#{file_path}.zip"
    Zip.unicode_names = true
    unless Rails.env == "development"
      system("LANG=ja_JP.SJIS")
    end

    Zip::ZipFile.open(file_path, Zip::ZipFile::CREATE) { |zipfile|
      files.to_a.each_with_index do |file,index|
        if file
          if File.exist?(file.file.path)
            zipfile.add( file.file_file_name.to_s.force_encoding("SHIFT_JIS"), file.file.path)
          end
        end
      end
    }
    logger.info file_path
    return file_path
  end
# linux线上环境调用linux自身command命令生成生成zip文件,zip命令
def self.zip_file_production(files)
    tmp_file_path = "#{Rails.root}/zip_file"
    date = "#{Time.now.strftime('%Y%m%d')}"
    rand_name = SecureRandom.hex
    path = File.join(tmp_file_path, date, rand_name)
    FileUtils.mkdir_p(path) unless File.exist?(path)

    files.to_a.each_with_index do |file,index|
      if file
        if File.exist?(file.file.path)
          FileUtils.cp(file.file.path, path) ## 将文件copy到path路径下
          logger.info file.file.path
        end
      end
    end

    # `/usr/local/bin/convmv -r -f utf8 -t sjis #{path} --notest`

    finally_file_name = "download.zip"
    logger.info finally_file_name
    logger.info path

    # logger.info "/usr/bin/7z a #{finally_file_name} #{path}"
    #system("LANG=en_US.UTF-8")
    system("cd #{path};zip -r #{finally_file_name} .")  ## 将path下的所有文件 压缩成 finally_file_name.zip文件
    return File.join(path,finally_file_name)
  end

 

posted @ 2021-08-26 14:22  鞋带松了  阅读(58)  评论(0编辑  收藏  举报