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 @   鞋带松了  阅读(60)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话
点击右上角即可分享
微信分享提示