项目总结_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("找不到指定文件,或文件已经删除");
        }

    }

 

转载于:https://www.cnblogs.com/JohnChen-happy/p/4570912.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值