Search code examples
javaapache-poiinputstreamhttpresponsefileoutputstream

Java outputstream, trigger file download before all data retrieved from db


Im trying to wrap my head around Java Out/Inputstreams, closing and flushing. I have a situation where I want to create a file using Apache POI with data from a server. I would like the file to start downloading as soon as I retrieve the first record from the DB(Show the file at the bottom of the browser has started to download).

public void createExcelFile(final HttpServletResponse response,
  final Long vendorId) {
    try {
      // setup responses types...

      final XSSFWorkbook xssfWorkbook = new XSSFWorkbook();
      final XSSFSheet sheet = xssfWorkbook.createSheet("sheets1");

      // create file with data
      writeExcelOutputData(sheet, xssfWorkbook);

      xssfWorkbook.write(response.getOutputStream());
      xssfWorkbook.close();
    }
    catch (final Exception e) {
      LOGGER.error("Boom");
    }

The above code will perform a file download no problem, but this could be a big file. I go off getting the data(around 20/30s) and then after that the download begins < no good...

Can I achive what I need or whats the best approach, thanks in advance

Cheers :)


Solution

  • Reasons could be as following:

    1. maybe there is a read/write timeout with your http server, then if the process gets lengthy or becasue of low-bandwidth, so the connection will be closed by the server.

    2. make sure the process(the excel work) gets completely done, maybe there would be an error/exception during work.

    The solution of Jorge looks very promising. User need once request for a file, then server would do the work in background and then either user check the work process and download the file if ready, or server informs the user by email, web notification, etc...

    Also you would keep the file in the server in a temp file for a while, and if the connection gets interrupted, server would respond the generated file partial(omit the bytes sent, like normal file download)

    Keeping a connection alive to do a lengthy work is not very logical.

    Again, if the file gets ready fast(really fast) for download/stream, and the download interrupts, if could be becasue of read/write timeout by server, or a very bad network.