Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails send multiple files to browser using send_data or send_file

I am trying to send multiple files to the browser. I cant call send_data for every record like in the code below because i get a double render error. According to this post i need to create the files and zip them so i can send them in one request.

@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

I am creating an array of hashes with the @json_encrypted and the file_name for each record. My question is how can i create a file for every record and then bundle them into a zip file to then pass that zip file to send_file. Or better yet have multiple file download dialogs pop up on the screen. One for each 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
like image 437
Joel Avatar asked Jul 24 '15 17:07

Joel


1 Answers

So the issue i was having is that send_file does not respond to an ajax call which is how i was posting to that action. I got rid of the ajax, and am sending the necessary data though a hidden_field_tag and submitting it with jquery. The code below creates files for the data, zips them, and passes the zip file to 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 
like image 77
Joel Avatar answered Sep 19 '22 15:09

Joel