struts 文件下载

50 篇文章 0 订阅
49 篇文章 0 订阅
以下代码是struts1中的action中
一般下载有三种方式,我常用的是这两种,做个记录

String dlpath = request.getParameter("dlpath");//文件相对路径
if(dlpath == null || "".equals(dlpath.trim())){
return null;
}

//得到下载文件名
//可能还会查询数据库中当初保存时的名字
String fileName = "";
if(dlpath.lastIndexOf("/") > 0) {
fileName = new String(dlpath.substring(dlpath.lastIndexOf("/")+1, dlpath.length()).getBytes("GB2312"), "ISO8859_1");
}else if(dlpath.lastIndexOf("\\") > 0) {
fileName = new String(dlpath.substring(dlpath.lastIndexOf("\\")+1, dlpath.length()).getBytes("GB2312"), "ISO8859_1");
}

response.reset();
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition", "attachment; filename=\""+fileName + "\"");

//=================第一种,相对最简单=====================
RequestDispatcher dispatcher = request.getRequestDispatcher(dlpath);
if(dispatcher != null){
dispatcher.forward(request,response);
}
response.flushBuffer();
//=================/第一种===============================

//=================第二种,输入/出流方式=====================
// File uploadFile = new File(request.getSession().getServletContext().getRealPath(dlpath));
// InputStream is = new FileInputStream(uploadFile);
// BufferedInputStream bis = new BufferedInputStream(is);
// OutputStream os = response.getOutputStream();
// BufferedOutputStream bos = new BufferedOutputStream(os);
//
// int bytesRead = 0;
// byte[] buffer = new byte[2048];
// while((bytesRead = bis.read(buffer,0,2048)) != -1){
// bos.write(buffer, 0, bytesRead);
// }
// bos.flush();
// is.close();
// bis.close();
// os.close();
// bos.close();
//==================/第二种============================================
return null ;


注意:
dlpath要以/开头,dispatcher才正确
response的设置和流的关闭,在struts action里的话,一定最后要返回null,因为在第一种方法里,dispatcher.forward后,不返回null,框架再返回就会出错,response已关闭
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值