Hello I'm doing File upload and download same file operation using JSF and Primefaces.
I'm using techniques from different forums and blogs combined(BelusC 's blog and Primefaces Showcase).
The main idea of this operation is to let user to upload a file and generate a Download link for the uploaded file so that he can download and see it before Submitting.
Here is my code:
index.xhtml
<h:form>
<p:fileUpload showButtons="false" label="Attach Refrral"
auto="true" fileUploadListener="#{fileBean.uploadListener}"/>
</h:form>
<h:form >
<p:commandLink>
See Uploaded File
<p:fileDownload value="#{fileBean.refrralFile}"/>
</p:commandLink>
</h:form>
FileBean.java
private StreamedContent refrralFile;
public void uploadListener(FileUploadEvent evt)throws Exception
{
UploadedFile fx = evt.getFile();
File mainDir = new File("C:/","fileStorage");
if(!mainDir.exists())
{
mainDir.mkdir();
}
File subDir = new File(mainDir,"AttachedRefrrals");
if(!subDir.exists())
{
subDir.mkdir();
}
String fileName = fx.getFileName();
File f = new File(subDir,fileName);
FileOutputStream fos = new FileOutputStream(f);
IOUtils.copy(fx.getInputstream(), fos);
InputStream is = ((ServletContext)FacesContext.getCurrentInstance().getExternalContext().getContext()).getResourceAsStream(f.getAbsolutePath());
refrralFile = new DefaultStreamedContent(is, new MimetypesFileTypeMap().getContentType(f), fileName);
}
public StreamedContent getRefrralFile() {
return refrralFile;
}
Using above code File is uploading Successfully but if I click file download link ths throwing exception:
java.lang.IllegalStateException: getOutputStream() has already been called for this response
I used FacesContext#responseComplete(), as its been suggested many places, now download link is not working at all.
Please correct me if I'm wrong in my technique or code and suggest any better way if you know.