zoukankan      html  css  js  c++  java
  • 项目总结_servlet中文下载时乱码中文文件名不能显示

    	response.setContentType("application/x-msdownload");
    //		response.setContentType("application/octet-stream");
    		response.setHeader("Content-Disposition", "attachment;filename="+
    new String(fileName.getBytes("utf-8"),"ISO-8859-1"));

    原因分析,由于HTTP头部的默认编码为ISO-8859-1而我们上传文件于下载文件过程中,提取到的文件名都要通过HTTP头部。

    所以我们需要在上传的时候对提取到的文件名进行转码为UTF-8,然后在下载时我们也要进行反向转码为ISO-8859-1.

        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            request.setCharacterEncoding("utf-8");
            response.setCharacterEncoding("utf-8");
            
            String realPath = request.getParameter("realPath");
            String filename= new String(request.getParameter("filename").getBytes("ISO-8859-1"),"utf-8");
            
            OutputStream out = response.getOutputStream();
            File file = new File(realPath+File.separator+filename);
            
            FileInputStream in = null;
            byte[] bytes = new byte[1024];
            if(file.exists()){
                
    //            response.setHeader("Content-disposition", "attachment;filename="+ filename);
                //response.setContentType("application/x-tar");
                //response.setContentType("application/x-msdownload");
                response.setContentType("application/octet-stream");
                response.setHeader("Content-Disposition", "attachment;filename="" + new String(filename.getBytes("utf-8"),"ISO-8859-1" )+ """);
                
                long fileLength = file.length();
                String length = String.valueOf(fileLength);
                response.setHeader("Content_Length", length);
                in = new FileInputStream(file);
                int n = 0;
                while ((n = in.read(bytes)) != -1) {
                    out.write(bytes, 0, n);
                }
                out.close();
            }else{
    /*            PrintWriter writer = response.getWriter();
                writer.println("找不到指定文件,或文件已经删除");
                writer.close();*/
    System.out.println("找不到指定文件,或文件已经删除");
            }
    
        }
  • 相关阅读:
    全局变量 和 局部变量
    函数
    字符串拼接
    集合
    字典
    元祖
    列表
    Python 字符串 小练习
    ssm多数据源配置
    JAVA笔记:double四舍五入并保留两位小数的方法
  • 原文地址:https://www.cnblogs.com/JohnChen-happy/p/4570912.html
Copyright © 2011-2022 走看看