bra*_*ter 6 java jsf jsp richfaces
我已经完成了以下工作:
现在我需要让第4步工作:
任何人都可以给我一个提示吗?我试图了解我在谷歌上发现的东西,但它并没有像预期的那样发挥作用.我是否必须设置内容类型?当我设置应用程序/八位字节流时,只有txt和csv文件才能正确显示(在浏览器中,而不是我想要的下载弹出窗口)其他文件无效...
JSP:
<a4j:commandLink value="Download" action="#{appController.downloadFile}" rendered="#{!file.directory}">
<f:param name="file" value="#{file.absoluteFilename}" />
</a4j:commandLink>
Run Code Online (Sandbox Code Playgroud)
AppController的:
public String downloadFile() {
String filename = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("file");
File file = new File(filename);
HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
writeOutContent(response, file, file.getName());
FacesContext.getCurrentInstance().responseComplete();
return null;
}
private void writeOutContent(final HttpServletResponse res, final File content, final String theFilename) {
if (content == null) {
return;
}
try {
res.setHeader("Pragma", "no-cache");
res.setDateHeader("Expires", 0);
res.setHeader("Content-disposition", "attachment; filename=" + theFilename);
FileInputStream fis = new FileInputStream(content);
ServletOutputStream os = res.getOutputStream();
int bt = fis.read();
while (bt != -1) {
os.write(bt);
bt = fis.read();
}
os.flush();
fis.close();
os.close();
} catch (final IOException ex) {
Logger.getLogger(ApplicationController.class.getName()).log(Level.SEVERE, null, ex);
}
}
Run Code Online (Sandbox Code Playgroud)
您的具体问题是您正在尝试通过Ajax下载文件.这是不正确的.JavaScript无法处理二进制响应,也没有任何强制执行另存为对话的工具.您需要将其设置为正常的同步请求,以便它是必须处理它的webbrowser本身.
<h:commandLink value="Download" action="#{appController.downloadFile}" rendered="#{!file.directory}">
<f:param name="file" value="#{file.absoluteFilename}" />
</h:commandLink>
Run Code Online (Sandbox Code Playgroud)
至于设置的内容类型,如果你有一个文件名以扩展在你的手中,你可以使用ServletContext#getMimeType()它基于解决<mime-mapping>中web.xml(无论是服务器的默认的一个或你的web应用的一个).
ServletContext servletContext = (ServletContext) externalContext.getContext();
String contentType = servletContext.getMimeType(file.getName());
if (contentType == null) {
contentType = "application/octet-stream";
}
response.setContentType(contentType);
// ...
Run Code Online (Sandbox Code Playgroud)
(请注意,我假设你正在使用JSF 1.x,看看你如何获得servlet响应,你可以,因为JSF 2.x否则也使用ExternalContext#getMimeType())
| 归档时间: |
|
| 查看次数: |
12888 次 |
| 最近记录: |