当前位置 : 主页 > 编程语言 > java >

java下载文件,中文文件名乱码特殊处理

来源:互联网 收集:自由互联 发布时间:2021-06-28
gistfile1.txt // 前台的中文传递后后台乱码的处理思路:// 1.js编码encodeURI(encodeURI(URL)),编码两次// 2.服务器端解码 URLDecoder.decode(request.getParameter("para"),"UTF-8")$scope.downloadProvinceModel = function
gistfile1.txt
//        	前台的中文传递后后台乱码的处理思路:
//         1.js编码encodeURI(encodeURI(URL)),编码两次
//         2.服务器端解码 URLDecoder.decode(request.getParameter("para"),"UTF-8")

$scope.downloadProvinceModel = function(){ 
    var url = ffc.context.contextPath + '/strc/reqChgOrderService/downloadFileByName?filename='+encodeURI(encodeURI("模型导入模板.xlsx"));
    window.location=url; 
};

@RequestMapping(value = "downloadFileByName")
public void downloadFileByName(HttpServletRequest request, HttpServletResponse response) {
    try {
        FileOperateUtil.FILEDIR = request.getSession().getServletContext().getRealPath("/") + "download/";
        String downloadfFileName = URLDecoder.decode(request.getParameter("filename"),"UTF-8");
        String fileName = downloadfFileName;
        //如果是IE8,9,10和IE11,则文件名称需要编码成UTF-8,其他浏览器无需处理
        if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0||request.getHeader("User-Agent").indexOf("like Gecko")>0) {  
            fileName = URLEncoder.encode(fileName, "UTF-8");
        }
        response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", fileName));
        FileOperateUtil.download(downloadfFileName, response.getOutputStream());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

    public static void download(String downloadfFileName, ServletOutputStream out) {
        try {
            FileInputStream in = new FileInputStream(new File(FILEDIR + "/" + downloadfFileName));
            write(in, out);
        } catch (FileNotFoundException e) {
            try {
                FileInputStream in = new FileInputStream(new File(FILEDIR + "/"
                        + new String(downloadfFileName.getBytes("iso-8859-1"),"utf-8")));
                write(in, out);
            } catch (IOException e1) {              
                e1.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }       
    }
上一篇:FastDFS工具类
下一篇:相机拍照代码
网友评论