JSP response對象實現檔案下載的兩種方式_JSP編程

來源:互聯網
上載者:User

一.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(); } %>
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.