Sevlet 下载pdf文件 支持中文文件名
package html2pdf.controller; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class DownloadServlet extends HttpServlet { private static final long serialVersionUID = 1L; public DownloadServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String fileName = "pdf文件.pdf"; // 要下载的文件名 // 通过文件名找出文件的所在目录 String path = "C:\Users\mail\eclipse-workspace\html2pdf\src\main\webapp\htmlReport"; // 得到要下载的文件 File file = new File(path + "\" + fileName); // 如果文件不存在 if (!file.exists()) { request.setAttribute("message", "您要下载的资源已被删除!"); request.getRequestDispatcher("/message.jsp").forward(request, response); return; } // 设置响应头,控制浏览器下载该文件 response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes("GBK"),"ISO8859_1")); // 支持中文文件名 FileInputStream in = new FileInputStream(path + "\" + fileName); // 读取要下载的文件,保存到文件输入流 OutputStream out = response.getOutputStream(); // 创建输出流 byte buffer[] = new byte[1024]; // 创建缓冲区 int len = 0; while ((len = in.read(buffer)) > 0) { // 循环将输入流中的内容读取到缓冲区当中 out.write(buffer, 0, len); // 输出缓冲区的内容到浏览器,实现文件下载 } in.close(); // 关闭文件输入流 out.close(); // 关闭输出流 } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
部署描述符
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>Archetype Created Web Application</display-name> <servlet> <servlet-name>DownloadServlet</servlet-name> <servlet-class>html2pdf.controller.DownloadServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>DownloadServlet</servlet-name> <url-pattern>/download</url-pattern> </servlet-mapping> </web-app>