当前位置: 代码迷 >> JavaScript >> JSF2.0怎么下载文件
  详细解决方案

JSF2.0怎么下载文件

热度:536   发布时间:2013-10-23 11:39:13.0
JSF2.0如何下载文件

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}" />