java web-文件下载

2 篇文章 0 订阅
@RequestMapping("/download")
public String download(String uploadpath,  HttpServletRequest request,
HttpServletResponse response) throws Exception {
// uploadpath是指欲下载的文件的路径。例如绝对路径是  /home/workspace/1.txt
File file = new File(uploadpath);
//获取文件名称,截取字符串,根据最后一个/截取,可取文件名称
int  endlength=uploadpath.lastIndexOf("/");
String filename=uploadpath.substring(endlength+1, uploadpath.length());
System.out.println("文件名称是:"+filename);
// 取得文件的后缀名。
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("UTF-8");
java.io.BufferedInputStream bis = null;
java.io.BufferedOutputStream bos = null;
try {
long fileLength = new File(uploadpath).length();
response.setContentType("application/x-msdownload;");     //设置下载的格式
response.setHeader("Content-Length", String.valueOf(fileLength));
//用来解决下载的文件名称乱码的问题,ISO8859-1格式可以避免下载文件名称字数限制的问题
response.setHeader("Content-disposition",
"attachment; filename=" + new String(filename.getBytes("utf-8"), "ISO8859-1"));
//读取文件
bis = new BufferedInputStream(new FileInputStream(uploadpath));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
//写入文件
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (bis != null)
bis.close();
if (bos != null)
bos.close();
}
return null;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值