jsfjsf-2downloadbacking-beans

How to provide a file download from a JSF backing bean?


Is there any way of providing a file download from a JSF backing bean action method? I have tried a lot of things. Main problem is that I cannot figure how to get the OutputStream of the response in order to write the file content to. I know how to do it with a Servlet, but this cannot be invoked from a JSF form and requires a new request.

How can I get the OutputStream of the response from the current FacesContext?


Solution

  • Introduction

    You can get everything through ExternalContext. There are a bunch of getResponseXxx() and setResponseXxx() methods which delegate to the HttpServletResponse being used under the covers.

    On the response, you should set the Content-Type header so that the client knows which application to associate with the provided file. And, you should set the Content-Length header so that the client can calculate the download progress, otherwise it will be unknown. And, you should set the Content-Disposition header to attachment if you want a Save As dialog, otherwise the client will attempt to display it inline. Finally just write the file content to the response output stream.

    Most important part is to call FacesContext#responseComplete() to inform Jakarta Faces that it should not perform navigation and rendering after you've written the file to the response, otherwise the end of the response will be polluted with the HTML content of the page, or in older Faces versions, you will get an IllegalStateException with a message like getoutputstream() has already been called for this response when the Faces implementation calls getWriter() to render HTML.

    Turn off Ajax!

    You only need to make sure that the action method is not called by an ajax request, but that it is called by a normal request as you fire with <h:commandLink> and <h:commandButton>. Ajax requests fired by <f:ajax>/<h:commandScript> are handled by JavaScript which in turn has, due to security reasons, by default no facilities to force a Save As dialogue with the content of the ajax response.

    In case you're using e.g. PrimeFaces <p:commandXxx>, then you need to make sure that you explicitly turn off ajax via ajax="false" attribute. The <p:remoteCommand> can also not be used. In case you're using ICEfaces, then you need to nest a <f:ajax disabled="true" /> in the command component.

    In case you're using PrimeFaces 10 or newer, then you can use <p:fileDownload> to simulate Ajax-like behavior when downloading a file, with onstart, update, oncomplete and all.

    Generic action method example

    <h:commandButton value="Download" action="#{bean.download}" />
    
    public void download() throws IOException {
        String fileName = ...;
        String contentType = ...;
        long contentLength = ...;
    
        FacesContext facesContext = FacesContext.getCurrentInstance();
        ExternalContext externalContext = facesContext.getExternalContext();
    
        externalContext.responseReset(); // Some Faces component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
        externalContext.setResponseContentType(contentType); // Check https://www.iana.org/assignments/media-types for all types.
        externalContext.setResponseContentLengthLong(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
        externalContext.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want.
    
        OutputStream output = externalContext.getResponseOutputStream();
    
        // Now you can write the InputStream of the file to the above OutputStream the usual way.
        // ...
    
        facesContext.responseComplete(); // Important! Otherwise Faces will attempt to render the response which obviously will fail since it's already written with a file and closed.
    }
    

    Common static file example

    In case you need to stream a static file from the local disk file system, substitute the code as below:

        File file = new File("/path/to/file.ext");
        String fileName = file.getName();
        String contentType = externalContext.getMimeType(fileName);
        long contentLength = file.length();
    
        // ...
    
        Files.copy(file.toPath(), output);
    

    Common dynamic file example

    In case you need to stream a dynamically generated file, such as PDF or XLS, then simply provide output there where the API being used expects an OutputStream.

    E.g. iText PDF:

        String fileName = "dynamic.pdf";
        String contentType = "application/pdf";
    
        // ...
    
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, output);
        document.open();
        // Build PDF content here.
        document.close();
    

    E.g. Apache POI HSSF:

        String fileName = "dynamic.xls";
        String contentType = "application/vnd.ms-excel";
    
        // ...
    
        HSSFWorkbook workbook = new HSSFWorkbook();
        // Build XLS content here.
        workbook.write(output);
        workbook.close();
    

    Note that you cannot set the content length here. So you need to remove the line to set response content length. This is technically no problem, the only disadvantage is that the enduser will be presented an unknown download progress. In case this is important, then you really need to write to a local (temporary) file first and then provide it as shown in previous chapter.

    Utility method

    If you're using Faces utility library OmniFaces, then you can use one of the three convenient Faces#sendFile() methods taking either Path, File, InputStream, or byte[], and specifying whether the file should be downloaded as an attachment (true) or inline (false).

    public void download() throws IOException {
        Faces.sendFile(path, true);
    }
    

    Yes, this code is complete as-is. You don't need to invoke responseComplete() and so on yourself. This method also properly deals with IE-specific headers and UTF-8 filenames. You can find source code here.