Bal*_*usC 24
如果它是一个简单的文件,只需放在公共webcontent(放置静态和JSF文件的地方)并创建一个链接.
<h:outputLink value="/files/file.ext">link</h:outputLink>
Run Code Online (Sandbox Code Playgroud)
servletcontainer将担心应用正确的标头.
如果出于某些特定原因(例如,在服务器计算机的固定路径或数据库中),它位于公共webcontent之外,那么创建一个获取InputStream
它的servlet并将其写入OutputStream
至少响应的响应Content-Type
,Content-Disposition
并且Content-Length
头.你可以在这里找到一个简单的启动示例.这也可以简单地链接在servlet上url-pattern
.
如果它是动态生成的并且取决于JSF特定的请求参数,那么您也可以在受到h:commandLink
或者绑定的托管bean操作中执行此操作h:commandButton
,但是您只需要确保FacesContext#responseComplete()
在bean的操作方法结束时调用以防止JSF从手中导航.可以重用相同类型的servlet代码来传输文件.您可以在此答案中找到启动示例.
Mar*_*ier 13
我需要制作类似的代码来通过JSF下载文件
这是我在JSF页面中的下载按钮
<h:commandButton value="Download" action="#{helloBean.downloadFile}" />
Run Code Online (Sandbox Code Playgroud)
这是我的Java代码
public void downloadFile() {
File file = new File("/home/marco/file.txt");
HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
response.setHeader("Content-Disposition", "attachment;filename=file.txt");
response.setContentLength((int) file.length());
ServletOutputStream out = null;
try {
FileInputStream input = new FileInputStream(file);
byte[] buffer = new byte[1024];
out = response.getOutputStream();
int i = 0;
while ((i = input.read(buffer)) != -1) {
out.write(buffer);
out.flush();
}
FacesContext.getCurrentInstance().getResponseComplete();
} catch (IOException err) {
err.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException err) {
err.printStackTrace();
}
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
54725 次 |
最近记录: |