使用 RubyZip 生成文件并下载为 zip

jl1*_*118 2 base64 ruby-on-rails file rubyzip zipfile

对于我的 Ruby on Rails 项目(Rails 版本 5.1.2),我正在生成图像文件 (png) 并使用 RubyZip gem 将它们下载为 zip 文件。

图像文件不存储在任何目录中。我有一个名为附件的模型。每个附件都有一个属性 image_string,它是图像的 base64 字符串。您可以使用标签显示图像image_tag(src = "data:image/jpeg;base64, #{attachment.image_string}", style: "border-radius: 0;")

对于多个图像,我想为每个图像创建临时文件而不将它们存储在任何地方并将这些图像下载为 zip 文件。

我现在拥有的代码:

def bulk_download
  require('zip')
  ::Zip::File.open("/tmp/mms.zip", Zip::File::CREATE) do |zipfile|
    Attachment.all.each do |attachment|
      image_file = Tempfile.new("#{attachment.created_at.in_time_zone}.png")
      image_file.write(attachment.image_string)
      zipfile.add("#{attachment.created_at.in_time_zone}.png", image_file.path)
    end
  end
  send_file "/tmp/mms.zip", type: 'application/zip', disposition: 'attachment', filename: "my_archive.zip"
  respond_to do |format |
    format.all { head :ok, content_type: "text/html" }
  end
end
Run Code Online (Sandbox Code Playgroud)

但是下载的zipfile里面没有文件,大小为0字节。提前致谢。

Wil*_*ill 7

您应该需要像这样关闭并取消链接 zip 文件:

require('zip')

class SomeController < ApplicationController
  # ...

  def bulk_download
    filename = 'my_archive.zip'
    temp_file = Tempfile.new(filename)

    begin
      Zip::OutputStream.open(temp_file) { |zos| }

      Zip::File.open(temp_file.path, Zip::File::CREATE) do |zip|
        Attachment.all.each do |attachment|
          image_file = Tempfile.new("#{attachment.created_at.in_time_zone}.png")
          image_file.write(attachment.image_string)
          zipfile.add("#{attachment.created_at.in_time_zone}.png", image_file.path)
        end
      end

      zip_data = File.read(temp_file.path)
      send_data(zip_data, type: 'application/zip', disposition: 'attachment', filename: filename)
    ensure # important steps below
      temp_file.close
      temp_file.unlink
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

这是我用作此代码来源的一篇很好的博客文章:https : //thinkingeek.com/2013/11/15/create-temporary-zip-file-send-response-rails/

此外,将所有库需求放在文件顶部(即require('zip'))是一种很好的做法。