• 下载文件时文件名是中文,文件名丢失或者乱码的问题


    解决方案

      针对不同浏览器类型,对文件名字做编码处理 Firefox (Base64) ;IE、Chrome ... 使用的是URLEncoder

    public class DownloadServlet2 extends HttpServlet {
    
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            //获取文件在tomcat下的路径
            String path = getServletContext().getRealPath("download/测试文档.txt");
    
            String fileName = "测试文档.txt";
            String clientType = req.getHeader("User-Agent");
            System.out.println(clientType);
            if(clientType.contains("Firefox")){
                fileName = base64EncodeFileName(fileName);
            }else{
                //IE ,或者  Chrome (谷歌浏览器) ,
                //对中文的名字进行编码处理
                fileName = URLEncoder.encode(fileName,"UTF-8");
            }
            //让浏览器收到这份资源的时候, 以下载的方式提醒用户,而不是直接展示
            resp.setHeader("Content-Disposition", "attachment; filename="+fileName);
            
            //转化成输入流
            InputStream is = new FileInputStream(path);
            OutputStream os = resp.getOutputStream();
            
            int len = 0;
            byte[] bts = new byte[1024];
            while ((len = is.read(bts)) != -1) {
                os.write(bts, 0, len);
            }
            os.close();
            is.close();
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doGet(req, resp);
        }
    
        public String base64EncodeFileName(String fileName) {
            BASE64Encoder base64Encoder = new BASE64Encoder();
            try {
                return "=?UTF-8?B?"
                        + new String(base64Encoder.encode(fileName
                                .getBytes("UTF-8"))) + "?=";
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
    }

  • 相关阅读:
    usaco 1.11
    当数组时全局变量时。。。怎样进行循环初始化
    hdu 1097 用到了位的移动
    hdu 1006
    HNOI2008]神奇的国度
    App测试基本流程详解(汇总整理)
    IOS测试Fastmonkey
    pytest+allure2+jenkins环境部署
    如何在cmd查看文件内容的md5值
    软件测试学习linux基础
  • 原文地址:https://www.cnblogs.com/qf123/p/10059023.html
Copyright © 2020-2023  润新知