Using Tempfile to create a zip file in rails

我是研究僧i 提交于 2019-12-13 13:16:10

问题


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

Currently I am doing this:

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

This generates following error:

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

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


回答1:


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



回答2:


So it doesn't actually look like you need or want a Tempfile. You really want a random path in the Rails.root/tmp directory. Try something like this:

zfpath = Rails.root.join('tmp', "somename-#{SecureRandom.hex(8)}.zip"
Zip::ZipFile.open(zfpath, Zip::ZipFile::CREATE) do |zipfile|
  zipfile.add(file, basepath + file)
end

Update:

While it's far more complex, you can find a discussion of how to do this with a Tempfile here - http://thinkingeek.com/2013/11/15/create-temporary-zip-file-send-response-rails/ .



来源:https://stackoverflow.com/questions/27577838/using-tempfile-to-create-a-zip-file-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!