1

I am using JSF and in one of the managed bean (view scope) i have a method as:

public String viewReport() {

        HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();

        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition","attachment;filename=book1.xls");

        try {
            File file = new File("C:\\soheb\\book1.xls");
            FileInputStream fileIn = new FileInputStream(file);
            ServletOutputStream out = response.getOutputStream();

            byte[] outputByte = new byte[4096];
            //copy binary contect to output stream
            while(fileIn.read(outputByte, 0, 4096) != -1)
            {
                out.write(outputByte, 0, 4096);
            }
            fileIn.close();
            out.flush();
            out.close();
        }
        catch(IOException e) {
            e.printStackTrace();
        }
        return null;
}

The excel which is getting retrieved is corrupted file. It has some strange characters above and below is the entire code of JSP. I even tried application/octet-stream for contenttype too.

I tried the same with a plain text file and i was able to open it through.

Please help me with this problem, Thanks in advance.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Soheb
  • 93
  • 2
  • 12

1 Answers1

1

It has some strange characters above

You need to reset the response beforehand.

response.reset();

Another possible cause is that the file being saved is corrupt by itself. E.g. saved using a Writer instead of OutputStream.


and below is the entire code of JSP

You need to tell JSF that you've already completed the response yourself so that it won't perform its default navigation and render response job after invoking the action method.

context.responseComplete();

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555