小编jl1*_*118的帖子

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

对于我的 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字节。提前致谢。

base64 ruby-on-rails file rubyzip zipfile

2
推荐指数
1
解决办法
3122
查看次数

标签 统计

base64 ×1

file ×1

ruby-on-rails ×1

rubyzip ×1

zipfile ×1