java文件下载以及中文乱码解决

  在客户端下载文件时替换下载文件的名称,但是当名称是中文时浏览器会出现乱码,解决代码如下:

    public org.springframework.http.ResponseEntity<InputStreamResource> handleExcel(HttpServletRequest request) throws Exception {
        String fileName = "模板下载.xsls";
            //解决浏览器下载汉字乱码的兼容问题
            String userAgent = request.getHeader("User-Agent");
            byte[] bytes = userAgent.contains("MSIE") ? fileName.getBytes() : fileName.getBytes("UTF-8");
            // 各浏览器基本都支持ISO编码
            String name = new String(bytes, "ISO-8859-1");
             //网络资源文件
             //可以替换为网络资源文件
             //本地文件
            PathResource file = new     PathResource(FileUtil.getNewFileName(fileName));
            HttpHeaders headers = new HttpHeaders();
            headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
            headers.add("Content-Disposition", "attachment;fileName=" + name);
            headers.add("Pragma", "no-cache");
            headers.add("Expires", "0");
            org.springframework.http.ResponseEntity<InputStreamResource> entity = org.springframework.http.ResponseEntity
                    .ok()
                    .headers(headers)
                    .contentLength(file.contentLength())
                    .contentType(MediaType.parseMediaType("application/octet-stream"))
                    .body(new InputStreamResource(file.getInputStream()));
            return entity;
}                    

  

posted @ 2019-01-14 10:49  羽哲  阅读(3772)  评论(0编辑  收藏  举报