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("找不到指定文件,或文件已经删除");
            }
    
        }
  • 相关阅读:
    TypeError: Buffer.alloc is not a function
    node.js服务端程序在Linux上持久运行
    C#中的反射
    群要事日记
    vs2017 自定义生成规则 错误 MSB3721 命令 ”已退出,返回代码为 1。
    VP9 Video Codec
    用户手册是Yasm汇编
    更改Mysql数据库存储位置
    注册表项
    C#开发可以可视化操作的windows服务
  • 原文地址:https://www.cnblogs.com/JohnChen-happy/p/4570912.html
Copyright © 2011-2022 走看看