zoukankan      html  css  js  c++  java
  • 下载文件时文件名是中文,文件名丢失或者乱码的问题

    解决方案

      针对不同浏览器类型,对文件名字做编码处理 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);
            }
        }
    }

  • 相关阅读:
    2.12 使用@DataProvider
    2.11 webdriver中使用 FileUtils ()
    Xcode8 添加PCH文件
    The app icon set "AppIcon" has an unassigned child告警
    Launch Image
    iOS App图标和启动画面尺寸
    iPhone屏幕尺寸、分辨率及适配
    Xcode下载失败 使用已购项目页面再试一次
    could not find developer disk image
    NSDate与 NSString 、long long类型的相互转化
  • 原文地址:https://www.cnblogs.com/qf123/p/10059023.html
Copyright © 2011-2022 走看看