1 //1.获取下载文件的路径 2 String filePath = "D:\\projects\\servlet-project\\servlet-response-download\\target\\classes\\img\\111.jpg"; 5 //2.获取文件名 6 String fileName = filePath.substring(filePath.lastIndexOf("\\") + 1); 7 //3、设置header 8 resp.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName,"utf-8")); 9 //4、设置下载文件的输入流 10 FileInputStream inputStream = new FileInputStream(filePath); 11 //5、创建缓冲区 12 int len = 0; 13 byte[] buff = new byte[1024]; 14 //6、获取输出流 15 ServletOutputStream outputStream = resp.getOutputStream(); 16 while ((len=inputStream.read(buff))>0) { 17 outputStream.write(buff,0,len); 18 } 19 inputStream.close(); 20 outputStream.close();22 }