Java的文件下载(通用)

/**
* 下载文件

* @param request
* @param response
* @return
*/
@RequestMapping(params = "downLoadFile")
public void downLoadFile(HttpServletRequest request, HttpServletResponse response) {
String localPath = getLocalPath();//这是本地上传路径(例如:D:/upload)
String filePath = getFilePath();//这个是web项目的相传路径,存数据库(例如:/uoload)
String path = request.getParameter("path");
String fileName = request.getParameter("fileName");
filePath = path.replaceFirst(filePath, localPath);//将数据库的文件上传路径改为本地的上传路径
File file = new File(filePath);
if(fileName == null || fileName.equals("")){
fileName = file.getName();
}
BufferedInputStream in = null;
ServletOutputStream out = null;
byte[] b;
if (!file.exists() || !file.isFile()) {
system.out.println("文件不存在,下载失败!");
}
response.reset();
// 1.设置文件ContentType类型,这样设置,会自动判断下载文件类型
response.setContentType("multipart/form-data");
// 2.设置文件头:最后一个参数是设置下载文件名(假如我们叫a.pdf)
try {
response.setHeader("Content-Disposition",
"attachment;fileName=" + new String(fileName.getBytes("utf-8"), "iso-8859-1"));
response.setCharacterEncoding("utf-8");
in = new BufferedInputStream(new FileInputStream(file));
b = new byte[1024];
out = response.getOutputStream();
int len = 0;
while ((len = in.read(b)) != -1) {
out.write(b, 0, len);
}
out.flush();
} catch (UnsupportedEncodingException e2) {
e2.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (in != null)
in.close();
if (out != null)
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值