Downloading Multiple Files in Java

Posted By : Ashish Sharma | 10-Oct-2013

Suppose that you have string array and want to download each of them in separate file.

String[] str = new String[5];
str[0] = "File1 Data";
str[1] = "File2 Data";
str[2] = "File3 Data";
str[3] = "File4 Data";
str[4] = "File5 Data";

If You want to download multiple number of files, you must add them to a zip file and then download it.

This code will create a zip file.

ByteArrayOutputStream baos = new ByteArrayOutputStream()
ZipOutputStream zipFile = new ZipOutputStream(baos)

Now run the loop for the files you want to add in the zip file, in grails you can use code below

for(int i =0;i<5;i++)
{ 
zipFile.putNextEntry(new ZipEntry("report"+i+".txt"));
zipFile << str[i];
zipFile.closeEntry();
}

in case of java you can use write() of ZipOutputStream

Now close the ZipOutputStream object and prepare the response header

zipFile.finish();
response.setContentType("APPLICATION/DOWNLOAD");
response.setHeader("Content-disposition", "attachment; filename=\"ZippedFile.zip\"")

To send the zip file as response in grails

response.outputStream << baos.toByteArray()

for sending response in java

response.getOutputStream().write(baos.toByteArray());

About Author

Author Image
Ashish Sharma

Ashish is a bright Groovy and Grails developer and have worked on development of various SaaS applications using Grails technologies. Ashish likes PC games and works out at Gym in his free time.

Request for Proposal

Name is required

Comment is required

Sending message..