JavaWeb中文件下载的代码,供参考
//文件下载 @WebServlet("/down") public class DownLoadServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //0.跳过权限检查和积分检查 //1.获取被下载的资源文件名称 String filename = req.getParameter("fileName"); System.out.println(filename); if (filename != null && "".equals(filename.trim())) { //对获取到的参数进行重新编码,因为可能会有中文乱码的问题 filename = new String(filename.getBytes("ISO-8859-1"), "utf-8"); System.out.println(filename); } //2.从服务器中找到被下载资源的绝对路径 String path = req.getServletContext().getRealPath("/WEB-INF/download/" + filename); System.out.println(path); // ---------------------------------------------------------------------------------------- //2.1告诉浏览器不要直接打开文件,而是弹出下载框,保存文件 resp.setContentType("application/x-msdownload"); //2.2应该设置下载文件的建议保存名称 //--------------------------------------------------------------------------------- String useragent = req.getHeader("User-Agent"); //下面两种方式谷歌浏览器全部都支持 if (useragent.contains("MSIE")) { //filename = URLEncoder.encode(filename, "UTF-8"); //System.out.println(filename); // IE浏览器的处理方式: resp.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8")); } else { //非IE浏览器的处理方式: //resp.setHeader("Content-Disposition", "attachment;filename="+(new String(filename.getBytes("utf-8"), "ISO-8859-1"))); filename = new String(filename.getBytes("utf-8"), "ISO-8859-1"); System.out.println(filename); } //--------------------------------------------------------------------------------- // 3.磁盘文件-->程序中-->响应给用户 Files.copy(Paths.get(path), resp.getOutputStream()); } }