//1.要获取下载文件的路径 String realPath = this.getServletContext().getRealPath("/1.png"); // String realPath="C:\\Users\\xiao\\Desktop\\tomcat\\apache-tomcat-9.0.60\\apache-tomcat-9.0.60\\webapps\\response_war\\1.png"; System.out.println("下载的路径:"+realPath); //2.下载的文件名是啥 String FileName = realPath.substring(realPath.lastIndexOf("\\") + 1); //3.设置让浏览器支持下载我们需要的东西 resp.setHeader("Content-disposition","attachment;filename="+ URLEncoder.encode(FileName,"UTF-8")); //4.获取下载文件的输入流 FileInputStream in = new FileInputStream(realPath); //5.创建缓冲区 int len=0; byte[] buffer=new byte[1024]; //6.获取outputStream对象 ServletOutputStream out = resp.getOutputStream(); //7.将Fileoutputstream流写到buffer缓冲区,使用outputsteam将缓冲区的数据输出到客户端 while((len=in.read(buffer))>0){ out.write(buffer,0,len); } in.close(); out.close();