JSP隐含对象response实现文件下载
|
一.简单介绍JSP隐含对象response实现文件下载 (1)在JSP中实现文件下载最简单的方法是定义超链接指向目标资源,用户单击超链接后直接下载资源,但直接暴露资源的URL也会带来一些负面的影响,例如容易被其它网站盗链,造成本地服务器下载负载过重。
<%@ 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:tomcatwebappsROOTd.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)文本文件下载 代码如下:
<%@ 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:tomcatwebappsROOTee.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实现文件下载有所帮助。 (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
