图片的路径在web/img下:
网页代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<a href="/ServletTest_war_exploded/downloadServlet?filename=img1.jpg">图片1</a>
</body>
</html>
servlet代码:
@WebServlet("/downloadServlet")
public class DownloadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1,获取请求参数
String filename=request.getParameter("filename");
//2,使用字节输入流加载文件进内存
//2.1找到文件服务器路径
ServletContext sc=this.getServletContext();
String rp = sc.getRealPath("/img/" + filename);
//2.2用字节流关联
FileInputStream fis=new FileInputStream(rp);
//3,设置response的响应头
//3.1设置响应头类型content-type
String mimeType = sc.getMimeType(filename);//获取文件的mime类型
response.setHeader("content-type",mimeType);
//3.2设置响应头打开方式content-disposition
response.setHeader("content-disposition","attachment;filename="+filename);
//4,将输入流的数据写出到输出流中
ServletOutputStream sos=response.getOutputStream();
byte[] buff=new byte[1024];
int len=0;
while((len=fis.read(buff))!=-1){
sos.write(buff,0,len);
}
fis.close();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}