• 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());
        }
    
    }
  • 相关阅读:
    数列分块入门九题(一):LOJ6277~6279
    Luogu P4211 [LNOI2014]LCA
    Luogu P2279 [HNOI2003]消防局的设立
    Luogu P3177 [HAOI2015]树上染色
    51Nod 1677 treecnt
    CYJian的水题大赛
    51Nod 1299 监狱逃离
    51Nod 1705 七星剑
    51Nod 1443 路径和树
    51Nod 1815 调查任务
  • 原文地址:https://www.cnblogs.com/djma/p/15176369.html
Copyright © 2020-2023  润新知