文件下载
可以下载任何格式的文件
@RequestMapping("/down")
public void down(HttpServletResponse response, HttpServletRequest request) throws IOException {
// String name = "Depot_Management/src/main/webapp/images/a.jpg";
// File f = new File(name);
//(request.getSession().getServletContext().getRealPath("/")+"/images/a.jpg")获取相对路径
File f = new File(request.getSession().getServletContext().getRealPath("/") + "/images/QQPCMgr_1100106221.exe");
System.out.println(f);
if (f.exists()) {
FileInputStream fis = new FileInputStream(f);
String filename = URLEncoder.encode(f.getName(), "utf-8"); //解决中文文件名下载后乱码的问题
byte[] b = new byte[fis.available()];
fis.read(b);
response.setCharacterEncoding("utf-8");
response.setHeader("Content-Disposition", "attachment; filename=" + filename + "");
//获取响应报文输出流对象
ServletOutputStream out = response.getOutputStream();
//输出
out.write(b);
//刷新
out.flush();
//关闭
out.close();
}
}
前端
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src="js/jquery-3.4.1.min.js"></script>
<script>
$(function () {
$("#id").click(function () {
var a =confirm("是否进行下载");
if (a==true){
return true;
}else {
return false;
}
})
})
</script>
</head>
<body>
<a href="down" id="id">文件</a>
</body>
</html>
访问:http://localhost:8080/down.jsp进行下载