文件下载中文乱码问题

最近用在做一个流程功能的文件上传下载功能时,发现部分IE浏览器上下载中文文件名文件时会出现文件名乱码的现象,使用谷歌完全没有问题,只是使用ie或以ie为内核的浏览器时会出现乱码问题,解决如下:

@GetMapping("/download")
    public void download( HttpServletRequest request, HttpServletResponse response,
                          @RequestParam(value = "pathName",required = false)String pathName) {
        String path = installService.findUrlByName(pathName);
        String suffix = pathName.substring(pathName.indexOf("."),pathName.length());
        if (suffix.equals(".jpg")||suffix.equals(".txt")||suffix.equals(".pdf")||suffix.equals(".png")||suffix.equals(".jpeg")){
            uploadPic(response,path);
        }else {
        try {
            downCfg(pathName, request, response);
            OutputStream out;
            FileInputStream inputStream = new FileInputStream(path);
            out = response.getOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = inputStream.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            inputStream.close();
            out.close();
            out.flush();
        } catch (IOException e) {
            //e.printStackTrace();
            }
        }
    }
  private void downCfg(String fileName, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        //判断浏览器对下载的文件处理乱码问题
        String userAgent = request.getHeader("User-Agent").toUpperCase();
        //IE或者以IE为内核的浏览器
        if (userAgent.contains("MSIE") || userAgent.contains("TRIDENT") || userAgent.contains("EDGE")) {
            fileName = URLEncoder.encode(fileName, "UTF-8");
            fileName = fileName.replace("+","%20");
        } else {
            //非IE浏览器
            fileName = new String(fileName.getBytes(), "ISO8859-1");
        }
        response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", fileName));
        response.setContentType("application/octet-stream;charset=utf-8");
        response.setCharacterEncoding("UTF-8");
    }

仅供参考!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值