本例介绍通过超链接下载文件到本例的简单实例。值得注意的是服务器文件目录的动态改变以及对相关字符串的处理。话不多说,直接上例子:
<%@ page import="java.io.*" %>
<%
String path = application.getRealPath("/")
String name = null
String i = request.getParameter("id")
if(i.equals("1")){
response.setHeader("content-disposition","attachment;filename=Roman0.mov")
name = "Roman0.mov"
}
if(i.equals("2")){
response.setHeader("content-disposition","attachment;filename=Roman1.mov")
name = "Roman1.mov"
}
if(i.equals("3")){
response.setHeader("content-disposition","attachment;filename=Roman2.mov")
name = "Roman2.mov"
}
response.setHeader("contentType","application/download")
out.clear()
out=pageContext.pushBody()
OutputStream ot = response.getOutputStream()
File f= new File(path+"\\download\\"+name)
System.out.print(path+"\\download\\"+name)
FileInputStream fin = new FileInputStream(f)
int x=fin.read()
while(x!=-1){
ot.write(x)
x=fin.read()
}
ot.close()
fin.close()
%>
文件下载完之后记得关闭连接,而且顺序尽量不作改动。