1. 用jsp页面实现了文件的下载:
<%@page language="java" contentType="application/x-msdownload"
pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<%@ page language="java" import="java.io.*"%>
<%@ page language="java" import="java.net.URLEncoder"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>下载文件</title>
</head>
<body>
<%
String docname = request.getParameter("docname");
String filedisplay = "";
//由于href链接不能使用中文,这里根据文件名判断是否需要改为中文
if (docname.equals("txt.txt") || docname.equals("word.doc") || docname.equals("excel.xls"))
{
filedisplay = "好友信息" + docname.substring(docname.lastIndexOf("."));
}
else
{
filedisplay = docname;//"给用户提供的下载文件名";
}
response.reset();//可以加也可以不加
response.setContentType("application/x-download");
String paths = pageContext.getServletContext().getRealPath("/");
String realPath = paths + "/download/";
String filedownload = realPath + docname;
filedisplay = URLEncoder.encode(filedisplay, "UTF-8");
response.addHeader("Content-Disposition", "attachment;filename=" + filedisplay);
//此处记得清理下。在释放在jsp中使用的对象时,会调用response.getWriter(),因为这个方法是和response.getOutputStream()相冲突的!
out.clear();
out = pageContext.pushBody();
OutputStream outp = null;
FileInputStream in = null;
try
{
outp = response.getOutputStream();
in = new FileInputStream(filedownload);
byte[] b = new byte[1024];
int i = 0;
while ((i = in.read(b)) > 0)
{
outp.write(b, 0, i);
}
outp.flush();
}
catch (Exception e)
{
System.out.println("Download Error!");
e.printStackTrace();
}
finally
{
if (in != null)
{
in.close();
in = null;
}
if (outp != null)
{
outp.close();
outp = null;
}
}
%>
</body>
</html>
2.添加相关的下载链接,后面跟的参数是下载文件名。例如:
<a href="../download/down.jsp?docname=soplus.apk" >下载</a>