一.简单介绍jsp隐含对象response实现文件下载
(1)在jsp中实现文件下载最简单的方法是定义超链接指向目标资源,用户单击超链接后直接下载资源,但直接暴露资源的url也会带来一些负面的影响,例如容易被其它网站盗链,造成本地服务器下载负载过重。
(2)另外一种下载文件的方法是使用文件输出流实现下载,首先通过response报头告知客户端浏览器,将接收到的信息另存为一个文件,然后用输出流对象给客户端传输文件数据,浏览器接收数据完毕后将数据另存为文件,这种下载方法的优点是服
务器端资源路径的保密性好,并可控制下载的流量以及日志登记等。
二.两种文件的下载方式
(1)二进制文件的下载
用jsp程序下载二进制文件的基本原理是:首先将源文件封装成字节输入流对象,通过该对象读取文件数据,获取response对象的字节输出流对象,通过输出流对象将二进制的字节数据传送给客户端。
1.把源文件封装成字节输入流对象
2.读取二进制字节数据并传输给客户端
代码如下:
<%@ 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能够输出字符数据。
代码如下:
<%@ 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();
}
%>
希望本文所述对大家学习jsp隐含对象response实现文件下载有所帮助。
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!