第一步:创建一个文件download.jsp,内容如下:
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ page import="com.fone.portal.pub.util.*"%>
<%
// example:
// <a href="download.jsp?url=img/test.gif">download image</a>
String root = getServletContext().getRealPath("/");
String fileUrl =request.getParameter("url");
if(fileUrl!=null&&!fileUrl.equals(""))
{
if(fileUrl.charAt(0)=='/')
{
fileUrl=fileUrl.substring(1,fileUrl.length());
}
String name=fileUrl;
int lastPosition=fileUrl.lastIndexOf("/");
if(lastPosition>=0&&lastPosition<fileUrl.length()-1)
{
name =fileUrl.substring(lastPosition+1,fileUrl.length());
}
java.io.File file = new java.io.File(root+fileUrl);
if (!file.exists()) {
out.write(M.getMessage("m.m.content.file.Download.notExist", null, request));
}
else
{
response.setContentType("unknown");
response.addHeader("Content-Disposition", "attachment;filename=/"" + name + "/"");
try
{
java.io.OutputStream os = response.getOutputStream();
java.io.FileInputStream fis = new java.io.FileInputStream(root+fileUrl);
byte[] b = new byte[1024];
int i = 0;
while ( (i = fis.read(b)) > 0 )
{
os.write(b, 0, i);
}
fis.close();
os.flush();
os.close();
response.flushBuffer();
out.clear();
out = pageContext.pushBody();
}
catch ( Exception e )
{
}
}
}
else
{
out.write(M.getMessage("m.m.content.file.Download.null.path", null, request));
}
%>
第二步、调用的时候,将url转到download.jsp,将文件的相对路径作为参数传给download.jsp即可,比如:
jsp调用:<a href="./../download.jsp?url=<%=FileUrl%>" target="_blank">下载</a>