如何实现下载文件之一:静态文件

187 篇文章 2 订阅
实验环境:JDeveloper 11.1.2.0.0。
说明:本文改自本人旧作,使用了目前最新的JDeveloper 11.1.2.0.0重新开发验证。(2011-8-3)

这里假设文件保存在服务器的某个目录下:比如C:/Temp。

1. 页面代码。
这里使用了一个参数:fileName,并给其赋了一个常量值。实际应用中,可以根据情况动态赋值。
注意在Managed Bean中如何获取该参数。
如果要使用f:param传递参数,只能使用CommandLink,而不能使用CommandButton。
<af:form id="f1">
<h:commandLink value="Download" id="cb1" actionListener="#{myBackingBean.downloadButton_actionListener}">
<f:param value="1.pdf" name="fileName" id="p1"/>
</h:commandLink>
</af:form>

2. 对应的Managed Bean代码。
public void downloadButton_actionListener(ActionEvent actionEvent) {
FacesContext facesContext = FacesContext.getCurrentInstance();
String fileName = (String)JSFUtils.getManagedBeanValue("param.fileName");
if (fileName != null) {
File file = new File(fileLocation + fileName);
String fileType = "aplication/octet-stream";
if (fileName.endsWith(".pdf")) {
fileType = "application/PDF";
} else if (fileName.endsWith(".doc")) {
fileType = "aplication/msword";
} else if (fileName.endsWith(".txt")) {
fileType = "text/plain";
} else if (fileName.endsWith(".ppt")) {
fileType = "application/vnd.ms-powerpoint";
} else if (fileName.endsWith(".rar")) {
fileType = "aplication/octet-stream";
} else if (fileName.endsWith(".zip")) {
fileType = "aplication/zip";
} else if (fileName.endsWith(".jpg")) {
fileType = "aplication/jpg";
} else {
fileType = "aplication/octet-stream";
}

if (file.exists()) {
ExternalContext extContext = facesContext.getExternalContext();
HttpServletResponse response = (HttpServletResponse)extContext.getResponse();
response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
response.setContentLength((int)file.length());
response.setBufferSize(1024);
response.setContentType(fileType);
//response.setContentType("application/x-download");

try {
InputStream in = new FileInputStream(file);
OutputStream out = response.getOutputStream();
writeInputStreamToOutputStream(in, out);
in.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
facesContext.responseComplete();
}
}

3. 运行页面。
(1)IE提示下载的窗口:


(2)Firefox提示打开和保存的窗口

(3)如果你的IE关联了迅雷这样的浏览器默认下载工具,你需要取消这个关联,方法是:工具->配置->监视设置->监视浏览器。

(4)facesContext.responseComplete();这行代码很重要,表明response结束了。

Project下载: DownloadFile2.7z

参考文献:
1. http://thepeninsulasedge.com/frank_nimphius/2007/08/18/adf-faces-direct-file-download-through-managed-bean/
2. http://blogs.oracle.com/smuenchadf/examples/#85
3. http://log-cd.javaeye.com/blog/415844
4. http://www.javaeye.com/topic/100066

5. http://pity1115.iteye.com/blog/336426


http://maping930883.blogspot.com/2010/07/adf091.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值