可视化jsf 实现文件下载

xwguan3 2008-05-19 05:18:57
在刚出来不就的netbeans6.0中有个fileupload控件,用该控件实现了文件上传以后,我要实现文件下载,怎么做?
...全文
221 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
小盘海 2010-02-25
  • 打赏
  • 举报
回复
试一下了,不知道行不呢
yexinjia8 2008-12-05
  • 打赏
  • 举报
回复
请问,你说的reponse.reset()非常重要;我想请问我的downFile()就没加那句,其他都跟你一样,结果点击down,进行相关操作后,再点jsp业务表单页面的保存时,会再次弹出下载提示框,请问是因为没加那句的缘故吗
xwguan3 2008-05-19
  • 打赏
  • 举报
回复
1楼给出的函数中第二个参数 HttpServletResponse 怎么用?
nanjg 2008-05-19
  • 打赏
  • 举报
回复
 public void downloadAction(ActionEvent event) {
try {
String fileName="D:\\temp\\images\\products\\" + this.id + ".xls";
logger.debug("file name=" + fileName);
ByteArrayOutputStream baos=this.serviceLocator.getFileService().downloadFile(fileName); //调用Service方法,获得文件的ByteArrayOutputStream
HttpServletResponse response=FacesUtils.getServletResponse();
response.setHeader("Content-disposition", "attachment; filename=" + id+ ".xls" ); //不是内嵌显示(inline),而是作为附件下载
response.setContentLength(baos.size());
ServletOutputStream sos=response.getOutputStream();
baos.writeTo(sos);
baos.close();
sos.flush();
} catch (IOException ex) {
logger.debug(ex);
}
}





<h:commandLink actionListener="#{productBean.downloadAction}" styleClass="highLightLink">
<h:outputText value="download"/>
<f:param name="productId" value="#{productBean.id}"/>
</h:commandLink>


出处http://blog.csdn.net/gohands/archive/2008/02/15/2096713.aspx
fengjinjizhi 2008-05-19
  • 打赏
  • 举报
回复
// 下载其实非常简单,只要如下处理,就不会发生问题。

public static void downLoad(String filePath, HttpServletResponse response,
boolean isOnLine) throws Exception {
File f = new File(filePath);
if (!f.exists()) {
response.sendError(404, "File not found!");
return;
}
BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
byte[] buf = new byte[1024];
int len = 0;

response.reset(); // 非常重要
if (isOnLine) { // 在线打开方式
URL u = new URL("file:///" + filePath);
response.setContentType(u.openConnection().getContentType());
response.setHeader("Content-Disposition", "inline; filename="
+ f.getName());
// 文件名应该编码成UTF-8
} else { // 纯下载方式
response.setContentType("application/x-msdownload;charset=gbk");
response.setHeader("Content-Disposition", "attachment; filename="
+ f.getName());
}
OutputStream out = response.getOutputStream();
while ((len = br.read(buf)) > 0)
out.write(buf, 0, len);
br.close();
out.close();
}

67,538

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧