public class FileServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String realPath = "F:\\ideaSpace\\New\\servletDemo\\src\\main\\resources\\1.png";
System.out.println("下载文件的路径:"+realPath);
String fileName = realPath.substring(realPath.lastIndexOf("\\")+1);
//F:\ideaSpace\New\servletDemo\src\main\resources\1.png
resp.setHeader("Content-Disposition","attachement;filename="+fileName);
FileInputStream in = new FileInputStream(realPath);
int len = 0;
byte[] buffer = new byte[1024];
ServletOutputStream out = resp.getOutputStream();
while((len=in.read(buffer))>0){
out.write(buffer,0,len);
}
in.close();
out.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}