下载文件

/** 
* 下载文件
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
*/
@SuppressWarnings("deprecation")
public ActionForward doDownload(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
FileForm fileForm = (FileForm) form;
OutputStream toClient = null;
try {
//测试--设置为固定路径
String path = request.getRealPath("/") + "upload//" + fileForm.getFileName();
File file = new File(path);
String filename = file.getName();
// 取得文件的扩展名
String ext = filename.substring(filename.lastIndexOf(".") + 1)
.toUpperCase();
InputStream fis = null;
try{
fis = new BufferedInputStream(new FileInputStream(path));
}catch(FileNotFoundException e){
e.printStackTrace();
System.out.println("系统没有找到指定文件");
}
if(fis==null){
response.getWriter().print("<script>alert('系统没有找到指定文件!');history.go(-1);</script>");
return null;
}
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
response.reset();
response.addHeader("Content-Disposition", "attachment;filename="
+ new String(filename.getBytes()));
response.addHeader("Content-Length", "" + file.length()); // 设置返回的文件类型
toClient = new BufferedOutputStream(response
.getOutputStream()); // 得到向客户端输出二进制数据的对象
// 根据扩展名声称客户端浏览器mime类型
if (ext.equals("DOC"))
response.setContentType("application/msword");
else
response.setContentType("application/octet-stream"); // 设置返回的文件类型
try{
if(toClient != null){
toClient.write(buffer); // 输出数据
toClient.flush();
}
}catch(Exception e){
e.printStackTrace();
System.out.println("用户取消下载文件...");
}
} catch (IOException ex) {
ex.printStackTrace();
} finally{
try {
if(toClient!=null){
toClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值