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

时间:2015-07-24 17:50:11

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

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

@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

1 个答案:

答案 0 :(得分:3)

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