1. 直接使用文件链接
<h:outputLinkvalue="#{request.contextPath}/resources/file/hello.pdf">
<h:graphicImagelibrary="images"name="pdf.jpg"style="border:none"/>
</h:outputLink>
2.使用stream
@ManagedBean
@RequestScoped
public class FileDownLoadBean {
public void down() throws IOException {
File file = new File("/home/sunjingchuan/Desktop/helloCoco.txt");
InputStream fis = new FileInputStream(file);
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext ec = fc.getExternalContext();
ec.responseReset();
ec.setResponseContentType("application/octet-stream");
ec.setResponseContentLength((int)file.length());
ec.setResponseHeader("Content-Disposition", "attachment; filename=helloCoco.txt");
OutputStream output = ec.getResponseOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while ((len = fis.read(buffer)) != -1) {
output.write(buffer, 0, len);
}
fis.close();
output.close();
fc.responseComplete();
}
}
页面可使用<h:commandLink>或<h:commandButton>
<h:commandLink value="download file" action="#{fileDownLoadBean.down}" />