日期:2014-05-17  浏览次数:20728 次

要下载服务器上的文件,下载应该怎么写
测试界面:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>

<html>
  <body>
  <form action="MyJsp.jsp" method="post" name="form">
<tr>
<td width="140">请输入路径:<input type="text" name="path"></td>
</tr>
<tr>
<td width="140">请输入文件名:<input type="text" name="name"></td>
</tr>
<input type="submit" name="submit" value="确认">
<input type="reset" value="取消">

</form>
<br>
  </body>
</html>



MyJsp.jsp下载页面:
<%@page contentType="text/html;charset=utf-8"%>
<%@ include file="common.jsp"%>
<%@ include file="connectdb.jsp"%>
<%@page language="java" import="java.net.*" pageEncoding="utf-8"%>
<%

String filenamedownload = request.getParameter("path"); //即将下载的文件的相对路径
String filenamedisplay = request.getParameter("name"); //下载文件时显示的文件保存名称

  response.setContentType("application/x-download");//设置为下载application/x-download
  filenamedisplay = URLEncoder.encode(filenamedisplay,"UTF-8");
response.addHeader("Content-Disposition", "attachment; filename=\"" + filenamedisplay + "\""); 
  try
  {
  RequestDispatcher dispatcher = application.getRequestDispatcher(filenamedownload);
  if(dispatcher != null)
  {
  dispatcher.forward(request,response);
  }
  response.flushBuffer();
  }
  catch(Exception e)
  {
  e.printStackTrace();
  }
  finally
  {
   
  }
%>



我输入路径为:D:\Tomcat 6.0\webapps\travel\file\b.txt
保存的文件名:a.txt
可是出错了

出错信息是:
java.lang.IllegalArgumentException: Path \Tomcat 6.0\webapps\travel\file\b.txt does not start with a "/" character
at org.apache.catalina.core.ApplicationContext.getRequestDispatcher(ApplicationContext.java:370)
at org.apache.catalina.core.ApplicationContextFacade.getRequestDispatcher(ApplicationContextFacade.java:196)
at org.apache.jsp.MyJsp_jsp._jspService(MyJsp_jsp.java:104)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:374)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:342)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter