**
SSM实现文件下载后台controller层实现代码
**
方式一
@ResponseBody
@RequestMapping("/downFile")
public void download(HttpServletRequest req, HttpServletResponse resp,String filename) throws IOException {
//获取文件的绝对路径名称
String path = req.getSession().getServletContext().getRealPath("/") + filename;
//转码,中文文件名要使用URLEncoder.encode方法进行编码
filename = URLEncoder.encode(filename,"UTF-8");
//设置文件下载头
resp.addHeader("Content-Disposition", "attachment;filename=" + filename);
//设置文件ContentType类型,这样设置会自动判断下载文件类型
resp.setContentType("multipart/form-data");
//读取要下载的文件,保存到文件输入流
FileInputStream in = new FileInputStream(path);
// 创建输出流
OutputStream out = resp.getOutputStream();
// 创建缓冲区 及 缓冲区的大小设置
byte[] buf = new byte[1024];
int len = 0;
//循环将输入流中的内容读取到缓冲区当中
while((len = in.read(buf)) > 0){
out.write(buf, 0, len);
}
//关闭文件输入流
in.close();
// 关闭输出流
out.close();
}
方式二
@ResponseBody
@RequestMapping("/downFile")
public void downloadFile(String filename,HttpServletRequest req, HttpServletResponse resp) throws IOException {
//Step1 前台用超链接触发下载功能,将要下载的文件名作为请求参数带上
<a href="${basePath}/user/downFile?filename=${user.yhtx}" id="pic_download">下载头像</a>
// Step2 后台接收请求,先设置响应头,表明为下载请求
resp.setHeader("Content-Disposition", "attachment;filename="+filename);
// Step3 获取文件的在硬盘上的绝对路径
String realPath = req.getServletContext().getRealPath("/");
// Step4 利用FileUtils将文件转成byte数组
File file = new File(realPath,filename);
byte[] bytes = FileUtils.readFileToByteArray(file);
// Step5 从相应对象中获取输出流,将byte数组写出
ServletOutputStream os = resp.getOutputStream();
os.write(bytes);
// Step6 清除输出流的缓存、关闭输出流
os.flush();
os.close();
}