使用ajax+servlet实现文件下载
前端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>
</head>
<body>
<button id="download" style="margin: 20px">下载图片</button>
<script>
$('#download').click(function () {
$.ajax({
type:"get",
url:"download.do",
success:function (data){
window.location.href=this.url;
}
})
})
</script>
</body>
</html>
后端代码
@WebServlet("/download.do")
public class DownloadFileServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String realPath = req.getServletContext().getRealPath("\\WEB-INF\\classes\\xiaomai.png");
String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
System.out.println(fileName);
//设置下载文件的响应头
// 为了防止文件名是中文响应回去时乱码使用URLEncoder.encode(fileName,"UTF-8")进行编码
resp.setHeader("Content-disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
FileInputStream input = new FileInputStream(realPath);
byte[] buff = new byte[1024];
int len =0;
ServletOutputStream out = resp.getOutputStream();
while ((len = input.read(buff))>0){
out.write(buff,0,len);
}
req.setAttribute("msg","hello");
input.close();
out.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}