zoukankan      html  css  js  c++  java
  • 下载中文文件乱码

    下载中文名称的文件时,文件会乱码,解决方式使用URLEncoder.encode编码

    例:

    /**
      * 下载担保书
      * @throws UnsupportedEncodingException
      */
     public void downLoadGurrentBook() throws UnsupportedEncodingException{
      String filePath = "";
      if("agent".equals(downLoadFileName)){
       filePath = ServletActionContext.getServletContext().getRealPath("/jsp/download/代理商担保书.doc");
      }else if("customer".equals(downLoadFileName)){
       filePath = ServletActionContext.getServletContext().getRealPath("/jsp/download/商户情况说明书.doc");
      }
      File file = new File(filePath);
      String fileName = file.getName();
      HttpServletResponse response = getHttpResponse();
      down(file, URLEncoder.encode(fileName,"UTF-8"), response);
     }
        public void down(File f,String filename,HttpServletResponse response)
        {
         response.reset();
         response.setHeader("content-disposition","attachment; filename="+filename); //设置下载的文件名
         long fileLength=f.length();
         String length1=String.valueOf(fileLength);
         response.setHeader("Content_Length",length1); //下载文件的大小
         InputStream in=null;
         OutputStream out = null;
         try{
          in = new FileInputStream( f );
          out = response.getOutputStream();
          byte[] buffer = new byte[2097152];
          int ins = in.read(buffer);//读取字节到buffer中
          //ins == -1 时 。就已经是文件的结尾了
          while ( ins != -1 ) {
           out.write(buffer, 0, ins);//将缓存buffer中的数据写到文件中
           ins = in.read(buffer);
          }
          in.close();
          out.flush();
          out.close();
         }catch (Exception e) {
             System.out.println("--下载发生异常--");
             try {
                        in.close();
                        out.flush();
                        out.close();
                    } catch (IOException e1) {
                        System.out.println("--关闭发生异常--");
                        in = null;
                        out = null;
                        e1.printStackTrace();
                    }
                }
        }

  • 相关阅读:
    《基于B_S模式的教务管理系统设计与实现》论文笔记(三)
    《重修补考报名考务管理信息系统中的网络技术》论文笔记(二)
    《基于WEB的独立学院补考重修管理系统研究》论文笔记(一)
    重修安排管理系统的设计与实现 文献收集
    重修安排管理系统的设计与实现 文献收集
    《暗时间》读书笔记
    R、Python、Scala 和 Java,到底该使用哪一种大数据编程语言?
    编程和音乐真的很像吗?
    关于虚拟现实叙事方式的终极入门指南
    如何避免脆弱的代码
  • 原文地址:https://www.cnblogs.com/siashan/p/4371918.html
Copyright © 2011-2022 走看看