在项目的资源目录下新建一个文件加,存放下载的文件
package com.guangtao.servlet; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.FileInputStream; import java.io.IOException; import java.net.URLEncoder; public class FileServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 1、获取要下载的文件 String realPath = "D:\Java_File\javaweb-maven-servlet\response\src\main\resources\广涛.png";
// 2、下载的文件命名是啥? 截取末尾的命名 String filename = realPath.substring(realPath.lastIndexOf("\") + 1); // 广涛.png
// 3、加入支持浏览器下载的请求头 // URLEncoder.encode(filename, "utf-8") 文件命名为中文则要设置编码格式 resp.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "utf-8"));
FileInputStream in = null; ServletOutputStream out = null; try { // 4、获取文件的流 in = new FileInputStream(realPath); // 5、创建缓冲区 int len = 0; byte[] buffer = new byte[1024]; // 6、输出流 out = resp.getOutputStream(); // 7、将FileOutputStream 流写入到buffer缓冲区,使用OutputStream将缓冲区中的数据输出到客户端 while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } } catch (IOException e) { e.printStackTrace(); } finally { // 关闭资源 if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } if (out != null) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }