一.步骤总结
1.接受下载资源的文件名称,根据文件名称找到磁盘对应的资源读取到内存中(形成输入流)
2.获取输出流
3.用IOUtils.copy将文件写出, 使用输出流对象将数据响应给浏览器(下载)
二.代码展示
后台代码
@Controller
public class DownLoad {
//String filename 接受下载资源的文件名称
@RequestMapping("/download")
public void download(String filename, HttpServletRequest request, HttpServletResponse response) throws IOException {
//文件名称找到磁盘对应的资源读取到内存中(形成输入流)
FileInputStream fis = new FileInputStream("c:/download/" + filename);
//获取输出流
ServletOutputStream ops = response.getOutputStream();
//可以通过请求的User-Agent 判断是否是IE,可以解决下载时文件名乱码的问题
String header = request.getHeader("User-Agent");
System.out.println(filename);
if (!header.contains("MSIE")) {
filename = new String(filename.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
}
//设置响应头
response.setHeader("Content-Disposition", "attachment;filename=" + filename);
System.out.println(filename);
IOUtils.copy(fis, ops);
}
}
前端代码
<a href="${pageContext.request.contextPath}/download.do?filename=dog.jpg">dog</a><br>
<a href="${pageContext.request.contextPath}/download.do?filename=狗.jpg">狗</a>