gpt4 book ai didi

ruby-on-rails - 使用 RubyZip 生成文件并下载为 zip

转载 作者:行者123 更新时间:2023-12-05 08:53:08 25 4
gpt4 key购买 nike

对于我的 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

但是下载的zip文件里面没有文件而且大小是0字节。提前致谢。

最佳答案

您应该像这样关闭并取消链接 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

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

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

关于ruby-on-rails - 使用 RubyZip 生成文件并下载为 zip,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54540190/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com