0

I am trying to download multiple files using OutputStream. I have created a for loop, looping through a Vector FileS which has file names and download them. But only the first file is getting downloaded. My Vector has FileZero.xml at 0 and FileOne.xml at 1 and only fileZero is getting downloaded. Please help; here's my code

        for (int x = 0; x < FileS.size(); x++) {
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            int nRead;
            byte[] data = new byte[1024];
            reportFile = rm.getClass().getResourceAsStream("/folder/" + FileS.elementAt(x));
            try {
                while ((nRead = reportFile.read(data, 0, data.length)) != -1) {
                    buffer.write(data, 0, nRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        buffer.flush();
        byte[] byteArray = buffer.toByteArray();

        try {

            byte bytes[] = null;
            bytes = byteArray;
            response.setContentLength(bytes.length);
            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "inline;filename=" + FileS.elementAt(x));
            OutputStream out = response.getOutputStream();
            out.write(bytes);
            out.flush();
            out.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    } catch (Exception e) {
       e.printStackTrace();
    }
}

Also, I tried commenting out out.flush() and out.close();but it didn't help. I tried putting the OutputStream object outside the loop just to test that also didn't help.

Paulo Mattos
  • 16,310
  • 10
  • 64
  • 73
Sidharth
  • 61
  • 1
  • 6

1 Answers1

2

Closing the output stream (on first iteration) and then trying to write to it (on the second one) is of course an error.

But even if you comment out out.close(), there is a problem: you setContent-Length` twice with lengths of individual files, but you output both files content, so the length must be the sum of the individual lengths.

Looks like you are trying to download both files in one request. The only reliable way is to pack them both into a single archive (like a ZIP archive) and download one file, see here: How to download multiple files with one HTTP request?

Or just download them one by one.

Roman Puchkovskiy
  • 9,798
  • 4
  • 25
  • 51
  • Yeah that makes sense but the link that you provided also gives an idea not a real solution on how to create zip file with multiple files inside. Thanks though – Sidharth Feb 25 '18 at 16:50