直接上代码
//1.获取文件要下载的路径
//String realPath = req.getServletContext().getRealPath("/1.jpg");
String realPath = "D:\\all\\programme\\JavaWeb\\Maven\\Servlet\\src\\main\\resources\\1.jpg";
System.out.println(realPath);
//2.下载的文件名称
String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
//3.想办法让浏览器可以支持下载我们需要的东西,中文名使用URLEncoder.encode(fileName,"UTF-8"))进行转义编码负责会乱码
resp.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
//4. 获取下载文件的输入流
FileInputStream fileInputStream = new FileInputStream(realPath);
//5. 创建缓冲区
int len = 0;
byte[] bytes = new byte[1014];
//6. 获取OutputStream()对象
ServletOutputStream outputStream = resp.getOutputStream();
//7. 将fileOutputStream流写入到buffer缓冲区,并使用OutputStream将缓冲区中的数据输入到客户端
while ((len = fileInputStream.read(bytes))>0){
outputStream.write(bytes,0,len);
}
//8. 关闭流
fileInputStream.close();
outputStream.close();