Search code examples
jsfdownloadplaintext

Binary file download generated in backing bean appears as plain text in client


I have server side webapp and I am trying to generate an excel file with Apache POI, which is provided as download by backing bean. I am able to write the file on server disk, but not to write it to HTTP response.

Here's my code

public void createExcel(){
    try {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        HSSFWorkbook workBook = new HSSFWorkbook();
        HSSFSheet sheet = workBook.createSheet("hello world");
        HSSFRow row = sheet.createRow((short) 0);
        HSSFCell cell;
        cell = row.createCell(0);
        cell.setCellValue(new HSSFRichTextString("Hello"));
        cell = row.createCell(1);
        cell.setCellValue(new HSSFRichTextString("world"));

        workBook.write(bos);
        bos.flush();

        FacesContext fc = FacesContext.getCurrentInstance();

        downloadExcel(bos, fc);
    } catch (FileNotFoundException e) {
        log.debug("file not found ", e);
    } catch (IOException e){
        log.debug("IOException ", e);
    }
}

public void downloadExcel(ByteArrayOutputStream baos, FacesContext fc){
    HttpServletResponse response = (HttpServletResponse)fc.getExternalContext().getResponse();
    response.setContentType("application/vnd.ms-excel");
    response.addHeader("Content-Disposition", "attachment; filename=testxls.xls");

    try {
        ServletOutputStream out = response.getOutputStream();
        baos.writeTo(out);

        out.flush();
        out.close();
    } catch (IOException e) {
        log.error("IOException ", e);
    }
    fc.responseComplete();
}

And the result is following

response

This happens in all browsers I tried: Chrome, FF and IE. I hope you can point out what I am missing here.


Solution

  • Finally found the solution in BalusC given link. I called createExcel() method in JSF inside <a4j:commandButton> tag, which called method through ajax. Changed it to <h:commandButton> and now it is working.