JSP程式中response物件實現檔案下載的兩種方式
這篇文章主要介紹了JSP隱含物件response實現檔案下載的兩種方法,很簡單,但很實用,需要的朋友可以參考下。
一.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();
}
%>