以下为download.jsp文件的代码:
<%@page contentType="text/html; charset=gb2312" language="java"%>
<%@page import="java.util.*"%>
<%@page import="java.io.*"%>
<%@page import="java.net.*"%>
<%
String fileName="";
String filePath = "d://max//";//下载文件目录,可以在配置文件中读取
if (request.getParameter("file") != null) {
fileName = request.getParameter("file");
}
response.reset();
response.setHeader("Content-disposition","attachment; filename="+fileName);
// response.setContentType("application/ms-excel");
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
System.out.println("Ready to transform file:"+filePath+fileName);
bis = new BufferedInputStream(new FileInputStream(filePath + fileName));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff,0,bytesRead);
System.out.println("Each time read content :"+buff.toString());
}
System.out.println("End of transform the file :"+fileName);
} catch(final IOException e) {
System.out.println ( "IOException." + e );
} finally {
if (bis != null)
bis.close();
if (bos != null)
bos.close();
}
%>
在test.jsp中使用方法如下:
<a href="./download.jsp?file=tunnel.rar" ><h1>download</h1></a>
这种方法可以下载所有类型的文件。
注意:若要直接使用link下载压缩文件,一般要使用zip格式,才能保证Browse正确下载,代码如下。
<a href="./file/tunnel.zip" ><h2>download1</h2></a>