终于解决了中文文件名文件下载的问题

        这是我的第一篇文章。

        今天终于解决了中文文件名文件下载的问题,在jsp页面中如果点击链接下载文件,英文文件没有问题,但是如果链接的是中文名文件,在下载的时候系统会报“找不到指定的目录或文件”的错误,研究了半天才搞定,以下是我的解决方案:

jsp是这样写的:这是其中显示文件列表的部分代码

<table border="1" style="border-collapse: collapse" cellspacing="0" cellpadding="0" width="542">
   <tr><th nowrap height="25" width="37" bordercolorlight="#698CC3" bordercolordark="#698CC3" background="../images/title_back.gif"><font color="#FFFFFF">
 序号</font></th>
   <th nowrap height="25" bordercolorlight="#698CC3" bordercolordark="#698CC3" background="../images/title_back.gif"><font color="#FFFFFF">
 文档列表</font></th></tr>
<%
   String path = request.getRealPath("//document");
   File file = new File(path);
   File[] files = file.listFiles();
  
   for(int i=0;i<files.length;i++)
   {
      if(files[i].isFile())
      {
     
   %>
     <tr>
        <td align=center width="37"><%=i+1%></td>
     <td height=25 width="469" align=center><a href="download2.do?file=<%=files[i].getName()%>"><%=files[i].getName()%></a></td>
  </tr>
   <%
      }
   }
%>
</table>

Action 代码:

    String filename = null;
    filename = request.getParameter("file");
    String file = this.getServlet().getServletContext().getRealPath("document/" +filename);
    try {
      filename = new String(filename.getBytes(), "ISO-8859-1");
    }
    catch (UnsupportedEncodingException ex1) {
      ex1.printStackTrace();
    }
    response.setContentType("application/octet-stream;charset=iso-8859-1");
    response.setHeader("Content-Disposition",
                       "attachment;filename=/"" + filename + "/";");
    FileInputStream fis = null;
    OutputStream os = null;
    try {
      fis = new FileInputStream(file);
      os = response.getOutputStream();
      byte[] buffer = new byte[2048];
      int readcount = 0;
      readcount = fis.read(buffer);
      while (readcount != -1) {
        os.write(buffer, 0, readcount);
        readcount = fis.read(buffer);
      }

      if (fis != null) {
        fis.close();
      }
      if (os != null) {
        os.close();
      }
      System.out.println(
          "------------------- Download complete -------------------");
    }
    catch (Exception ex) {
      ex.printStackTrace();
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值