【问题标题】:Rails send multiple files to browser using send_data or send_fileRails 使用 send_data 或 send_file 将多个文件发送到浏览器
【发布时间】:2015-07-24 17:50:11
【问题描述】:

我正在尝试将多个文件发送到浏览器。我不能像下面的代码那样为每条记录调用 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

【问题讨论】:

  • 您可能想要查看 Rubyzip gem (github.com/rubyzip/rubyzip),否则如果您真的想要下载多个单个文件,我认为您可以在打开多个 URL 的页面上使用一些 JS它指向您身边的视图,并带有相应的“强制下载”标题。
  • @evotpid 感谢您的回复!我会调查的

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


【解决方案1】:

所以我遇到的问题是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 

【讨论】:

    猜你喜欢
    • 2011-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-01
    • 2016-04-09
    • 1970-01-01
    • 2011-04-13
    • 1970-01-01
    相关资源
    最近更新 更多