NPE在primefaces中的filedownload

时间:2011-08-12 10:47:09

标签: download primefaces

我对此File Download Does Not Work有类似的问题。但是,我已经尝试了所有建议的答案,但无济于事。我还有一个NEP。有人可以帮忙吗

这是我的控制器类:

@ManagedBean(name = "fileDownLoadController")
@RequestScoped
public class FileDownloadController {

private StreamedContent downloadFile;

public FileDownloadController() {
    InputStream stream = null;
    ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();



        File result = new File(extContext.getRealPath("//WEB-INF//temp//process.png"));

        File outFile = new File("process.png");
        Logger.getLogger(FileDownloadController.class.getName()).log(Level.SEVERE, outFile.getAbsolutePath());

        stream = extContext.getResourceAsStream(result.getAbsolutePath());

        downloadFile = new DefaultStreamedContent(stream, "image/png", "process.png");

}

public StreamedContent getFile() {
    return downloadFile;
}

public void setFile(StreamedContent file) {

        this.downloadFile = file;

}

查看代码:

                <h1 class="title">FileDownload</h1>

            <div class="entry">
                <p>FileDownload </p>

                <h:form>

                    <p:commandButton value="Download" ajax="false" >
                        <p:fileDownload value="#{fileDownloadController.file}" />
                    </p:commandButton>

                </h:form>

            </div>

以下是错误消息:

java.lang.NullPointerException
at org.primefaces.component.filedownload.FileDownloadActionListener.processAction(FileDownloadActionListener.java:53)
at javax.faces.event.ActionEvent.processListener(ActionEvent.java:88)
at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:769)
at javax.faces.component.UICommand.broadcast(UICommand.java:300)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)

1 个答案:

答案 0 :(得分:1)

问题在于stream = extContext.getResourceAsStream(result.getAbsolutePath())。请注意,在这种情况下,文件不在类路径中,就像您提到的另一个文件一样。看下面,它应该工作 -

public FileDownloadController() throws FileNotFoundException {         
    ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();        
    File result = new File(extContext.getRealPath("//WEB-INF//temp//process.png"));        
    InputStream stream = new FileInputStream(result.getAbsolutePath());
    downloadFile = new DefaultStreamedContent(stream, "image/png", "process.png");
}