zoukankan      html  css  js  c++  java
  • 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());
        }
    
    }
  • 相关阅读:
    2019-2020-1学期20192401《网络空间安全专业导论》第一周学习总结
    14201771010119穷吉
    13201771010119穷吉
    12穷吉201771010119
    11201771010119穷吉
    实验10穷吉201771010119
    实验九201771010119穷吉
    201771010119穷吉第八周
    七次201771010119穷吉
    实验六20177101010119穷吉
  • 原文地址:https://www.cnblogs.com/djma/p/15176369.html
Copyright © 2011-2022 走看看