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

时间:2024-03-01 10:33:00

 

解决方案

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