您好,我正在使用 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>
文件Bean.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;
}
使用上面的代码文件上传成功,但如果我单击文件下载链接,则会引发异常:
java.lang.IllegalStateException: getOutputStream() has already been called for this response
I used FacesContext#responseComplete()正如很多地方所建议的那样,现在下载链接根本不起作用。
如果我的技术或代码有错误,请纠正我,并在您知道的情况下提出更好的方法。