如何从JSF后台bean提供文件下载?有没有从JSF后台bean操作方法提供文件下载的方法?我试过很多东西。主要问题是我不知道如何获得OutputStream的响应,以便将文件内容写入。我知道怎么用Servlet,但是这不能从JSF表单中调用,并且需要一个新的请求。我怎么才能拿到OutputStream当前的响应FacesContext?
3 回答
达令说
TA贡献1821条经验 获得超6个赞
public void downloadFile(String filename) throws IOException { final FacesContext fc = FacesContext.getCurrentInstance(); final ExternalContext externalContext = fc.getExternalContext(); final File file = new File(filename); externalContext.responseReset(); externalContext.setResponseContentType(ContentType.APPLICATION_OCTET_STREAM.getMimeType()); externalContext.setResponseContentLength(Long.valueOf(file.lastModified()).intValue()); externalContext.setResponseHeader("Content-Disposition", "attachment;filename=" + file.getName()); final HttpServletResponse response = (HttpServletResponse) externalContext.getResponse(); FileInputStream input = new FileInputStream(file); byte[] buffer = new byte[1024]; final ServletOutputStream out = response.getOutputStream(); while ((input.read(buffer)) != -1) { out.write(buffer); } out.flush(); fc.responseComplete();}
添加回答
举报
0/150
提交
取消