6

I'm currently trying to send multiple files outside of my application using Rails send_file method. It loops through all of the files, but only sends the last one in the directory. Here is my code.

  Dir.foreach(@dir) do |entry|
    if entry != "." && entry != ".." && entry != ".DS_Store" && entry != ".title"
      send_file(@dir + entry, :disposition => 'inline')
      logger.info("File: " + @dir + entry)
    end
  end

Any help is appreciated!

2 Answers 2

5

send_file tells the controller that it should respond to the browser's request by sending a file. -- As opposed to rendering a view, sending JSON, etc.

In common usage, you send exactly one response in HTTP. (I'm omitting discussion of long-polling and other esoteric types of responses. I'm also omitting HTTP multipart responses which are not generally supported at this time.)

Since you can only send one file, make it count! The one file can be a zip of a number of files, but then the user will need to unzip them.

An alternative is to show multiple download links on the web page, inviting the user to download one after another to accomplish the multiple downloads.

As an example UX (User Experience): Send an email to yourself with multiple attachments. Then use GMail and see how they present the multiple files for you to download.

Sign up to request clarification or add additional context in comments.

4 Comments

HTTP has had multi-part responses, so while a single request is met with a single response, it isn't necessarily a single document that gets returned. Browser support for multipart messages is pretty bad, unfortunately, but it's incorrect to imply this is a limitation of HTTP.
@coreyward -- good point about the protocol spec. I've updated the answer.
@LarryK how would you show multiple download links on the web page using send_file. I get a DoubleRenderError when i try that.
You would have multiple links on your page. Each link is for a different download. The first link will download file a, the 2nd is for file b. Each response to a link uses send_file to return 1 file.
1

You can only send a single file in a single request; if you want to send multiple files you need to zip them up or otherwise bundle them.

2 Comments

could you elaborate a little more? If I would like to send multiple files to the browser with send_data. How would i go about that? Would i zip them individually and pass the zipped file to send_data? Thanks ahead of time
@JoelL That's what I state in the answer; you can bundle them up and send them together.

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.