介绍一个非常好用的下载文件的方法,自己控制流不如让容器去控制流,呵呵还可以使用下载工具下载,
jsp文件只有两个参数,下载对话框提示要保存的文件名和文件做在服务器上面的相对路径,点击后页面不会跳转会弹出文件保存对话框,还可以目标另存为或使用下载工具下载.
<a herf='X.jsp?fileName=a.doc&filePath=x/a.doc'>点击下载</a>
<%
String filePath = " / " + request.getParameter( " filePath " );
String fileName = request.getParameter( " fileName " );
if (fileName == null || filePath == null )
return ;
response.setContentType( " application/x-download " );
response.addHeader( " Content-Disposition " , " attachment;filename= " + java.net.URLEncoder.encode(fileName, " UTF-8 " ));
try {
RequestDispatcher dis = application.getRequestDispatcher(filePath);
if (dis != null ){
dis.forward(request,response);
}
response.flushBuffer();
} catch (Exception e){
e.printStackTrace();
} finally {
}
%>
String filePath = " / " + request.getParameter( " filePath " );
String fileName = request.getParameter( " fileName " );
if (fileName == null || filePath == null )
return ;
response.setContentType( " application/x-download " );
response.addHeader( " Content-Disposition " , " attachment;filename= " + java.net.URLEncoder.encode(fileName, " UTF-8 " ));
try {
RequestDispatcher dis = application.getRequestDispatcher(filePath);
if (dis != null ){
dis.forward(request,response);
}
response.flushBuffer();
} catch (Exception e){
e.printStackTrace();
} finally {
}
%>