8

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
2
  • You might want to look into the Rubyzip gem (github.com/rubyzip/rubyzip) otherwise if you really want to do multiple single file downloads I think you could do that with some JS on a page where multiple URLs get opened which point to views on your side with corresponding "download forcing" headers. Commented Jul 24, 2015 at 20:27
  • @evotopid thanks for the response! Ill look into that Commented Jul 24, 2015 at 20:30

1 Answer 1

5

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 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.