0
votes

I'm using Apache POI to generate document with .docx extension. I set the file name in the header response (HttpServletResponse), but the browser saves a file with same name at the end of my URL, example:

URL in my browser is: localhost:8080/MyProject/mypage.jsf, the name of the downloaded file is mypage.jsf, ignoring the name set in the header (HttpServletResponse). If I edit the file extension for docx, content is OK.

Here's the code:

    private void generateDocument() throws IOException{
      XWPFDocument document = new XWPFDocument();
      //load document here

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

        response.reset();
        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");

        ServletOutputStream out = response.getOutputStream();
        document.write(out);

        response.setHeader("Content-Disposition",
                "attachment; filename=my_document.docx");
        facesContext.responseComplete();            
}

Ps. I'm using Richfaces 4

Thanks

1
Did you try moving the response.setHeader call to before you write to the servlet output stream? I don't know about your servlet setup, but in most all headers need to go before writing the contentGagravarr
Also, don't forget to flush the output stream and close it before setting the response complete.Luiggi Mendoza
@Gagravarr, it worked! Luiggi Mendoza, really is necessary. Thanks all.vctlzac

1 Answers

0
votes

Promoting from a comment to an answer:

You should move the response.setHeader call to before you write to the servlet output stream. Unless your framework is doing an epic amount of buffering, then the framework will have sent the response headers long before you finish writing the excel file to the stream. The headers have to get sent before the data, so as soon as you start sending data you can no longer add new headers.

(Most frameworks do a tiny bit of buffering, so when working with simple textual output you can often sneak a few extra headers in even after you write out a few lines of response. It's best not to rely on this if you can avoid it!)

Your code should be changed to be:

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

    response.reset();
    response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
    response.setHeader("Content-Disposition",
            "attachment; filename=my_document.docx");

    ServletOutputStream out = response.getOutputStream();
    document.write(out);

    facesContext.responseComplete();