主要使用到的是文件的输入和输出流和缓冲区
课程代码:
1 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 2 3 // 下载文件的路径 4 String realPath = "/Users/zhouxiaoming/workspace/code/java/javaweb-02-servlet-test2/response/target/classes/周.png"; 5 System.out.println("要下载文件的路径:" + realPath); 6 7 // 下载的文件名 8 String fileName = realPath.substring(realPath.lastIndexOf("/") + 1); 9 10 // 设置下载的头信息和编码 11 resp.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8")); 12 // 获取下载文件的输入流 13 FileInputStream in = new FileInputStream(realPath); 14 15 // 创建缓冲区 16 int len =0; 17 byte[] buffer = new byte[1024]; 18 19 // 获取OutputStream对象 20 ServletOutputStream out = resp.getOutputStream(); 21 // 将输入流写到缓冲区,使用OutputStream将数据输出到浏览器 22 while((len = in.read(buffer)) > 0){ 23 out.write(buffer, 0 , len); 24 } 25 26 in.close(); 27 out.close(); 28 29 }
原文:https://www.cnblogs.com/nuyan/p/14533721.html