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();
                    }
                }
        }

  • 相关阅读:
    Sort
    MyOD
    Linux C语言编程基础(必做)
    团队作业(一):团队展示
    2.3.1测试
    《Unix/Linux系统编程》第四章学习笔记
    课堂测试2
    课堂测试
    第三章 Unix/Linux进程管理学习笔记
    团队作业(二):需求分析
  • 原文地址:https://www.cnblogs.com/siashan/p/4371918.html
Copyright © 2011-2022 走看看