一.JSP隐含对象response实现文件下载的介绍
(1)在JSP中实现文件下载最简单的方法是定义超链接指向目标资源,用户单击超链接后直接下载资源,但直接暴露资源的URL
也会带来一些负面的影响,例如容易被其它网站盗链,造成本地服务器下载负载过重。
(2)另外一种下载文件的方法是使用文件输出流实现下载,首先通过response报头告知客户端浏览器,将接收到的信息另存
为一个文件,然后用输出流对象给客户端传输文件数据,浏览器接收数据完毕后将数据另存为文件,这种下载方法的优点是服
务器端资源路径的保密性好,并可控制下载的流量以及日志登记等。
二.以下介绍两种文件的下载方式
(1)二进制文件的下载
用JSP程序下载二进制文件的基本原理是:首先将源文件封装成字节输入流对象,通过该对象读取文件数据,获取response对象
的字节输出流对象,通过输出流对象将二进制的字节数据传送给客户端。
1.把源文件封装成字节输入流对象
2.读取二进制字节数据并传输给客户端
代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
<%@ page contentType=
"application/x-download"
import
=
"java.io.*"
%>
<%
int
status=
0
;
byte
b[]=
new
byte
[
1024
];
FileInputStream in=
null
;
ServletOutputStream out2=
null
;
try
{
response.setHeader(
"content-disposition"
,
"attachment; filename=d.zip"
);
in=
new
FileInputStream(
"c:\\tomcat\\webapps\\ROOT\\d.zip"
);
out2=response.getOutputStream();
while
(status != -
1
)
{
status=in.read(b);
out2.write(b);
}
out2.flush();
}
catch
(Exception e)
{
System.out.println(e);
response.sendRedirect(
"downError.jsp"
);
}
finally
{
if
(in!=
null
)
in.close();
if
(out2 !=
null
)
out2.close();
}
%>
|
(2)文本文件下载
文本文件下载时用的是字符流,而不是字节流。首先取得源文件的字符输入流对象,用java.io.FileReader类封装,
再把FileReader对象封装为java.io.BufferedReader,以方便从文本文件中一次读取一行。字符输出流直接用JSP的隐
含对象out,out能够输出字符数据。
代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
<%@ page contentType=
"application/x-download"
import
=
"java.io.*"
%><%
int
status=
0
;
String temp=
null
;
FileReader in=
null
;
BufferedReader in2=
null
;
try
{
response.setHeader(
"content-disposition"
,
"attachment; filename=ee.txt"
);
response.setCharacterEncoding(
"gb2312"
);
in=
new
FileReader(
"c:\\tomcat\\webapps\\ROOT\\ee.txt"
);
in2=
new
BufferedReader(in);
while
((temp=in2.readLine()) !=
null
)
{
out.println(temp);
}
out.close();
}
catch
(Exception e)
{
System.out.println(e);
response.sendRedirect(
"downError.jsp"
);
}
finally
{
if
(in2!=
null
)
in2.close();
}
%>
|