Search code examples
jsf-2primefaces

Primefaces filedownload error handling


How to handle error with primefaces filedownload

<p:fileDownload value="#{testBean.file}" /> 

TestBean.java

    public StreamedContent getFile() {  
    if(selectedReport ==null){
        FacesContext.getCurrentInstance().addMessage(.."Please select a file");
        return null;//What to do here
    }
    InputStream inps =  ReportGenerator.getPDF(selectedReport);
    return new DefaultStreamedContent(inps, "application/pdf", "report.pdf"); 
    }

Solution

  • This helped http://forum.primefaces.org/viewtopic.php?f=3&t=8263

    <p:commandButton    ajax="false"
                        value="Download Detailed Report"
                        actionListener="#{reportBean.generateDetailedReport}">
    
        <p:fileDownload value="#{reportBean.detailedReport}"/>
    
    </p:commandButton>
    
    public void generateDetailedReport(ActionEvent ae) {
    
        ......
    
        reportStream = ExcelReport.generate(reportList);
    
        if (reportStream == null) {
    
            FacesUtil.addError("Error generating report");
    
            throw new AbortProcessingException();
        }
    }
    
    public StreamedContent getDetailedReport() {
    
        return new DefaultStreamedContent(reportStream, "application/xls", "report.xls"); 
    }