NPE on filedownload in primefaces
I开发者_如何转开发 have a similar problem to this File Download Does Not Work. However, I have tried all the answers suggested but to no avail. I still get a NEP. Can someone please help
Here is my controller class:
@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;
}
View code:
<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>
Here is the error message:
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)
Problem is with stream = extContext.getResourceAsStream(result.getAbsolutePath())
. Note that the file is not in the classpath in this case like in the other one you mentioned. Look below, it should work -
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");
}
精彩评论