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

来源:互联网 发布:java编程实例pdf 编辑:程序博客网 时间:2024/05/19 09:02

        这是我的第一篇文章。

        今天终于解决了中文文件名文件下载的问题,在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();
    }