jsf 附件上载代码
前台页面大概如下:
<h:commandLink value="下载" action="#{KnowledgeItemAction.download}">
<f:param name="fileName" value="#{file.saveName}"/>
<f:param name="testPath" value="${facesContext.externalContext.requestContextPath}"/>
</h:commandLink>
后台代码如下:
public void download() {
String str = FacesContext.getCurrentInstance().getExternalContext()
.getRequestParameterMap().get( "fileName" );
if(null != str ){
String filePath = Util.PATH + str; // 得到文件路径
try {
FacesContext ctx = FacesContext.getCurrentInstance();
ctx.responseComplete(); //此步必须有否则会出现:Servlet response already use stream
异常HttpServletResponse response=(HttpServletResponse)ctx.getExternalContext().getResponse();
File f = new File(filePath);
if (!f.exists()) {
response.sendError(404, "File not found!");
return;
}
BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
byte[] buf = new byte[1024];
int len = 0;
response.reset(); // 非常重要
response.setContentType("application/x-msdownload;charset=gbk");
response.setHeader("Content-Disposition", "attachment; filename="
+ f.getName());
OutputStream out = response.getOutputStream();
while ((len = br.read(buf)) > 0)
out.write(buf, 0, len);
br.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}