Sending multiple files in single HTTP response using Java Servlet
Sometimes you may need to send multiple files in response to an HTTP request. There may be different use cases requiring it: sending a set of selected files to the user, sending the configuration package that contains multiple files etc. Unfortunately, this is not possible with HTTP because it is clearly request-response protocol. Theoretically it is possible to either use an external download manager tool (like Sun Download manager and others) or write a complicated AJAX-based solution that initiates the downloading of one file after another. However, this is too complicated and the convenience for the end user is questionable.
The easiest way to solve the problem is to send multiple files in one archive, building it on the fly (ZIP for the general audience and TAR for real geeks ;) ). It is very easy to create a Java servlet that dynamically builds an archive and feeds it into the HTTP response. You can get the sample code here.
Just a couple of comments about the code. First of all, setting correct content type is very important. This allows the browser to launch the appropriate application (like WinZip on Windows) when downloading the file.
response.setContentType("application/zip");
In order to set the suggested file name for the data being downloaded, you can use "Content-Disposition" header.
I like using Commons IO library for I/O operations. It provides a number of convenient methods simplifying the code and allowing to avoid to code the same simple operations again and again. The best examples are:
// copying one stream to another up to the end IOUtils.copy(inStream, outStream); ... // attempting to close the stream regardless of // its state, ignoring any exceptions IOUtils.closeQuietly(aStream);
Of course, the code like this should never be used in the environment where you may expect a high number of users downloading large amounts of data - you will be unable to provide enough threads to serve them all! If that is your case, you need to look at the asynchronous solutions (like Continuations).
 ### References
blog comments powered by Disqus