使用 Tempfile 在 rails 中创建一个 zip 文件 [英] Using Tempfile to create a zip file in rails

查看:27
本文介绍了使用 Tempfile 在 rails 中创建一个 zip 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 rails 中创建一个临时的 .zip.为了创建 zip 文件,我使用了 rubyzip gem.

I want to create a temporary .zip in rails. For creating zip file I am using rubyzip gem.

目前我正在这样做:

zfname = Tempfile.new(['somename','.zip'], Rails.root.to_s + '/tmp/')
Zip::ZipFile.open(zfname.path, Zip::ZipFile::CREATE) do |zipfile|
  zipfile.add(file, basepath + file)
end

这会产生以下错误:

Zip::ZipError: Zip end of central directory signature not found

是否可以将 Tempfile 用于 zip?如果是,这里有什么问题?

Is it possible to use Tempfile for zip? If yes, what is wrong here?

推荐答案

在我的 rails 应用程序中,当我需要向用户发送 zip 文件时,我只是将它们存储在缓冲区中并在控制器中使用发送数据"方法.我最初尝试使用Tempfile",但它有一个附加任务,即在将 zip 文件发送给用户后删除它,这很痛苦.这是您要找的东西吗?

In my rails app when I needed to send zip files to user, I just stored them in a buffer and used 'send data' method in controller. I was trying to use 'Tempfile' initially but it had an added task of removing zip files after sending it to user which is a pain. Is this something you are looking for?

    Zip::OutputStream.write_buffer do |stream|
      file_paths.each_with_index do |file_path, index|
        # rename the pdf
        stream.put_next_entry("#{name}-#{index + 1}.pdf")
        # add pdf to zip
        stream.write IO.read(file_path)
      end  
    end

这篇关于使用 Tempfile 在 rails 中创建一个 zip 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆