您好,我正在使用 JSF 和 Primefaces 进行文件上传和下载相同的文件操作。
我正在使用来自不同论坛和博客的技术(BelusC 的博客和 Primefaces Showcase)。
这个操作的主要思想是让用户上传一个文件,并为上传的文件生成一个下载链接,以便他可以在提交之前下载并看到它。
这是我的代码:
索引.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;
}
使用上面的代码文件上传成功但是如果我点击文件下载链接ths抛出异常:
java.lang.IllegalStateException: getOutputStream() has already been called for this response
我使用了FacesContext#responseComplete(),因为它被建议很多地方,现在下载链接根本不起作用。
如果我的技术或代码有误,请纠正我,如果您知道,请提出更好的方法。