2

This code creates a workbook and send it to client browser. It's almost fine, response is sent back to browser and a nice popup opens up in browser asking to save, open file, or cancel the whole operation. Classic.

The thing is, if I debug this code, sometimes, and only in IE, java machine will get stucked on line wb.write(out); (but I still have my excel file sent to client, I can download it and it's ok).

Problem is I wanted to put some code after this line, so sometimes it's not executed.

Any clue ?

public static void export(List<ExportSheetData> exportSheetsData, String fileName) throws IOException {

    FacesContext context = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext()
            .getResponse();
    response.setContentType("application/vnd.ms-excel");
    String headerResponse = "attachment;filename=";
    headerResponse = headerResponse.concat(fileName);
    response.addHeader("Content-disposition", headerResponse);
    ServletOutputStream out = response.getOutputStream();

    Workbook wb = new XSSFWorkbook();
    for (ExportSheetData exportSheetData : exportSheetsData) {
        Sheet sheet = wb.createSheet(exportSheetData.getTitle());
                    // creating workbook here...
    }

    wb.write(out); // JVM sometimes get stucked here
    out.flush();
    out.close();
    context.responseComplete();

}
Mat
  • 1,309
  • 1
  • 20
  • 43

1 Answers1

3

JVM stops here because nothing reads from the stream on the other side. Next line will be executed after whole file is downloaded. Firefox, Opera and Chrome starts download before you click "save". When you click "cancel" - the file is deleted. IE waits with download for your click.

I had similiar problem once and I've created another Thread that was writing to a stream while this thread wa doing something else.

You can also try to wrap output stream into a BufferedOutputStream. It should work if the file is small enough and fits into a buffer.

Piotr Gwiazda
  • 12,080
  • 13
  • 60
  • 91