ruby-on-rails - Rails 使用 send_data 或 send_file 将多个文件发送到浏览器

标签 ruby-on-rails ruby zip temporary-files

我正在尝试向浏览器发送多个文件。我不能像下面的代码一样为每条记录调用 send_data,因为我收到双重渲染错误。根据this post我需要创建文件并压缩它们,以便我可以在一个请求中发送它们。

@records.each do |r|
  ActiveRecord::Base.include_root_in_json = true
  @json = r.to_json
  a = ActiveSupport::MessageEncryptor.new(Rails.application.config.secret_token)
  @json_encrypted = a.encrypt_and_sign(@json)
  send_data @json_encrypted, :filename => "#{r.name}.json" }
end

我正在为每条记录创建一个包含 @json_encryptedfile_name 的哈希数组。我的问题是如何为每条记录创建一个文件,然后将它们打包成一个 zip 文件,然后将该 zip 文件传递​​给 send_file。或者更好的是在屏幕上弹出多个文件下载对话框。每个文件一个。

file_data = []
@records.each do |r|
    ActiveRecord::Base.include_root_in_json = true
    @json = r.to_json
    a = ActiveSupport::MessageEncryptor.new(Rails.application.config.secret_token)
    @json_encrypted = a.encrypt_and_sign(@json)
    file_data << { json_encrypted: @json_encrypted, filename: "#{r.name}.json" }
end

最佳答案

所以我遇到的问题是 send_file 没有响应 ajax 调用,这就是我发布到该操作的方式。我摆脱了 ajax,并通过 hidden_​​field_tag 发送必要的数据并使用 jquery 提交。下面的代码为数据创建文件,压缩它们,并将压缩文件传递给 send_data。

file_data.each do |hash|
  hash.each do |key, value| 
    if key == :json_encrypted
      @data = value
    elsif key == :filename
      @file_name = value
    end
  end

  name = "#{Rails.root}/export_multiple/#{@file_name}"
  File.open(name, "w+") {|f| f.write(@data)}

  `zip -r export_selected "export_multiple/#{@file_name}"`
  send_file "#{Rails.root}/export_selected.zip", type: "application/zip",  disposition: 'attachment' 
end 

关于ruby-on-rails - Rails 使用 send_data 或 send_file 将多个文件发送到浏览器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31616788/

相关文章:

python - 将 zip 文件中的固定宽度文本文件读取到 Pandas 数据框中

django - uWSGI 和 Django 段错误

css - 如何根据用户输入创建动态 CSS

ruby-on-rails - Stripe Webhook在Rails上

ruby - 在该 .map 代码块中引用 .map 返回对象(数组)?

ruby-on-rails - 在现有项目上使用 Rails 设置 postgresql 数据库

Ruby 按条件搜索哈希

c# - 使用 System.IO.Packaging 生成 ZIP 文件

ruby-on-rails - Rails 窗体 : how to store two text_fields in one array

ruby-on-rails - rails 与 Oauth : multiple providers