javaweb 文件名下载乱码问题终极解决方案

简介: 之前看很多博客都是通过 判断userAgent来处理文件名的中文乱码问题,如下 if (userAgent.indexOf("MSIE")!=-1 || userAgent.

之前看很多博客都是通过 判断userAgent来处理文件名的中文乱码问题,如下

 if (userAgent.indexOf("MSIE")!=-1 || userAgent.indexOf("Trident")!=-1 || userAgent.indexOf("Edge")!=-1 ) {     // ie  
   fileName = new String(fileName.getBytes("GBK"), "iso-8859-1");  
                   } else if (null != userAgent && -1 != userAgent.indexOf("Mozilla")) {           // 火狐,chrome等  
                       fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");  
                   } 

但博主实际开发中发现,这种也不是百分之百有效,最简单粗暴的方式就是把fileName 先BASE64编码存为url,然后下载时候再把fileName用BASE64解码,就可以规避浏览器对中文编码不一致的问题了,代码如下:

package com.nercel.cyberhouse.ws.sns;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import com.alibaba.fastjson.JSON;
import com.nercel.cyberhouse.util.ServerConfig;
import com.nercel.cyberhouse.vo.UFile;
import com.nercel.cyberhouse.vo.UploadFile;
import java.util.regex.*; 

@Controller
@RequestMapping("sns")
public class FileUpload {
    private String CYBERHOUSE_PATH =  ServerConfig.get("cyberhouse.root");

       @RequestMapping(value = "/uploadFile", produces = "text/plain; charset=utf-8")
       public @ResponseBody String uploadFile(@RequestParam(value = "file", required = false) MultipartFile file,int userId,HttpServletRequest request, HttpServletResponse response) {  
            UploadFile upFile = new UploadFile();
            String path = request.getSession().getServletContext().getRealPath("upload/sns/"+userId+"/");  
          //  String fileName = StringFilter(file.getOriginalFilename());
            String fileName = file.getOriginalFilename();
            String ext=fileName.substring(fileName.lastIndexOf(".")+1);

            if(file.getSize()>1024*1024*50){
                upFile.setCode(1);
                upFile.setMsg("单个文件/图片大小不能超过50M!");
                return JSON.toJSONString(upFile);
            }
            String name=UUID.randomUUID().toString()+"."+ext;
            String downLoadPath=path+"/"+name;
            File targetFile = new File(path,name);  
            if(!targetFile.exists()){  
                targetFile.mkdirs();  
            }  
           try {  
              file.transferTo(targetFile);  
              upFile.setCode(0);
              UFile uf=new UFile();
              uf.setName(fileName);
              byte[] b = null;  
              b = fileName.getBytes("utf-8");  
              uf.setSrc(CYBERHOUSE_PATH+"/sns/downLoadFile?downLoadPath="+downLoadPath+"&fileName="+new BASE64Encoder().encode(b));
              upFile.setData(uf);
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
            return JSON.toJSONString(upFile);    
      }


        @RequestMapping("/downLoadFile")  
        public void downLoadFile(String downLoadPath, String fileName,HttpServletResponse response,HttpServletRequest request) throws UnsupportedEncodingException {  
             BufferedInputStream bis = null;  
                BufferedOutputStream bos = null;          
                byte[] b = null;  
                String resultFileName = null;  
                    BASE64Decoder decoder = new BASE64Decoder();  
                        try {
                            b = decoder.decodeBuffer(fileName);
                        } catch (IOException e1) {
                            e1.printStackTrace();
                        }  
                        resultFileName = new String(b, "utf-8");  

                try {  
                    response.setCharacterEncoding("UTF-8"); 

                    long fileLength = new File(downLoadPath).length();
                    String userAgent = request.getHeader("User-Agent");                
                    response.setHeader("Content-disposition", "attachment; filename="+new String(resultFileName.getBytes("gbk"),"iso-8859-1"));
                    response.setContentType("application/x-download;");

                    response.setHeader("Content-Length", String.valueOf(fileLength));  
                    bis = new BufferedInputStream(new FileInputStream(downLoadPath));  
                    bos = new BufferedOutputStream(response.getOutputStream());  
                    byte[] buff = new byte[2048];  
                    int bytesRead;  
                    while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {  
                        bos.write(buff, 0, bytesRead);  
                    }  
                    bos.flush();  
                } catch (Exception e) {  
                } finally {  
                    if (bis != null) {  
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }  
                    if (bos != null) {  
                        try {
                            bos.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }  
                    }  
                }  
        }  

       // 过滤特殊字符  
       public static String StringFilter(String str) throws PatternSyntaxException{     
              // 清除掉所有特殊字符和空格
              String regEx="[`~!@#$%^&*()+=|{}':;',\\[\\]<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、? ]";  
              Pattern p = Pattern.compile(regEx);     
              Matcher m = p.matcher(str);     
              return m.replaceAll("").trim();     
       }

       //layui上传文件公共服务
       @RequestMapping(value = "/upload", produces = "text/plain; charset=utf-8")
       public @ResponseBody String upload(@RequestParam(value = "file", required = false) MultipartFile file,HttpServletRequest request, HttpServletResponse response) {  
            UploadFile upFile = new UploadFile();

            String msg="上传失败!";
            long fileSize = file.getSize();
            System.out.println("fileSize="+fileSize);

            if(fileSize>2097152){
                upFile.setCode(1);
                upFile.setMsg("上传文件不能超过2M!");
                return JSON.toJSONString(upFile);   
            }

            String fileName = StringFilter(file.getOriginalFilename());
            String fileType= fileName.substring(fileName.lastIndexOf(".")+1);
            Date now = new Date(); 
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");//可以方便地修改日期格式
            String today = dateFormat.format(now); 
            String path = request.getSession().getServletContext().getRealPath("upload/layuiUploads/"+fileType+"/"+today);
            String name=UUID.randomUUID().toString()+fileName;
            String downLoadPath=path+"/"+name;
            File targetFile = new File(path,name);  
            if(!targetFile.exists()){  
                targetFile.mkdirs();  
            }  
           try {  
              file.transferTo(targetFile);
              upFile.setCode(0);
              UFile uf=new UFile();
              uf.setName(fileName);
              uf.setSrc(CYBERHOUSE_PATH+"/sns/downLoadFile?downLoadPath="+downLoadPath+"&fileName="+fileName);
              upFile.setData(uf);
              msg="上传成功!";
              upFile.setMsg(msg);
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
           System.out.println(JSON.toJSONString(upFile));
            return JSON.toJSONString(upFile);    
      }

}
目录
相关文章
基于JavaWeb的销售管理系统设计系统
本系统基于Java、MySQL、Spring Boot与Vue.js技术,构建高效、可扩展的销售管理平台,实现客户、订单、数据可视化等全流程自动化管理,提升企业运营效率与决策能力。
|
Java Unix Go
【Java】(8)Stream流、文件File相关操作,IO的含义与运用
Java 为 I/O 提供了强大的而灵活的支持,使其更广泛地应用到文件传输和网络编程中。!但本节讲述最基本的和流与 I/O 相关的功能。我们将通过一个个例子来学习这些功能。
509 1
|
人工智能 自然语言处理 Java
FastExcel:开源的 JAVA 解析 Excel 工具,集成 AI 通过自然语言处理 Excel 文件,完全兼容 EasyExcel
FastExcel 是一款基于 Java 的高性能 Excel 处理工具,专注于优化大规模数据处理,提供简洁易用的 API 和流式操作能力,支持从 EasyExcel 无缝迁移。
4359 65
FastExcel:开源的 JAVA 解析 Excel 工具,集成 AI 通过自然语言处理 Excel 文件,完全兼容 EasyExcel
|
监控 Java API
Java语言按文件创建日期排序及获取最新文件的技术
这段代码实现了文件创建时间的读取、文件列表的获取与排序以及获取最新文件的需求。它具备良好的效率和可读性,对于绝大多数处理文件属性相关的需求来说足够健壮。在实际应用中,根据具体情况,可能还需要进一步处理如访问权限不足、文件系统不支持某些属性等边界情况。
696 14
|
存储 Java 数据安全/隐私保护
Java技术栈揭秘:Base64加密和解密文件的实战案例
以上就是我们今天关于Java实现Base64编码和解码的实战案例介绍。希望能对你有所帮助。还有更多知识等待你去探索和学习,让我们一同努力,继续前行!
1069 5
|
SQL 前端开发 Java
JavaWeb 学习日记案例详解及 javaweb 完整项目案例实战指南
本文介绍了一个基于Spring Boot的JavaWeb企业员工管理系统完整案例,涵盖部门管理、员工管理、登录、异常处理、事务管理及AOP等核心功能实现,结合CSDN相关技术文章,提供详细技术方案与应用实例,适合JavaWeb开发者学习与参考。
890 0
|
前端开发 Cloud Native Java
Java||Springboot读取本地目录的文件和文件结构,读取服务器文档目录数据供前端渲染的API实现
博客不应该只有代码和解决方案,重点应该在于给出解决方案的同时分享思维模式,只有思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~
Java||Springboot读取本地目录的文件和文件结构,读取服务器文档目录数据供前端渲染的API实现
|
存储 Java 编译器
深入理解Java虚拟机--类文件结构
本内容介绍了Java虚拟机与Class文件的关系及其内部结构。Class文件是一种与语言无关的二进制格式,包含JVM指令集、符号表等信息。无论使用何种语言,只要能生成符合规范的Class文件,即可在JVM上运行。文章详细解析了Class文件的组成,包括魔数、版本号、常量池、访问标志、类索引、字段表、方法表和属性表等,并说明其在Java编译与运行过程中的作用。
487 0
|
存储 人工智能 Java
java之通过Http下载文件
本文介绍了使用Java实现通过文件链接下载文件到本地的方法,主要涉及URL、HttpURLConnection及输入输出流的操作。
953 0
|
存储 算法 Java
解锁“分享文件”高效密码:探秘 Java 二叉搜索树算法
在信息爆炸的时代,文件分享至关重要。二叉搜索树(BST)以其高效的查找性能,为文件分享优化提供了新路径。本文聚焦Java环境下BST的应用,介绍其基础结构、实现示例及进阶优化。BST通过有序节点快速定位文件,结合自平衡树、多线程和权限管理,大幅提升文件分享效率与安全性。代码示例展示了文件插入与查找的基本操作,适用于大规模并发场景,确保分享过程流畅高效。掌握BST算法,助力文件分享创新发展。