java、javascript實現附件下載樣本

來源:互聯網
上載者:User

java、javascript實現附件下載樣本

 在web開發中,經常需要開發“下載”這一模組,以下給出一個簡單的例子。

在伺服器端,使用java開發:

01 @RequestMapping(value = "download.html", method = RequestMethod.GET) 

02 public void download(String resourceid, HttpServletRequest request, HttpServletResponse response) { 

03 response.setContentType("charset=UTF-8"); 

04 File file = new File(path); 

05 response.setHeader("Content-Disposition", "attachment; filename=a"); 

06 BufferedInputStream bis = null; 

07 BufferedOutputStream bos = null; 

08 OutputStream fos = null; 

09 InputStream fis = null; 

10 try { 

11 fis = new FileInputStream(file.getAbsolutePath()); 

12 bis = new BufferedInputStream(fis); 

13 fos = response.getOutputStream(); 

14 bos = new BufferedOutputStream(fos); 

15 int bytesRead = 0; 

16 byte[] buffer = new byte[5 * 1024]; 

17 while ((bytesRead = bis.read(buffer)) != -1) { 

18 bos.write(buffer, 0, bytesRead); 

19

20 bos.flush(); 

21 }catch(E e){ 

22 }finally { 

23 try { 

24 bis.close(); 

25 bos.close(); 

26 fos.close(); 

27 fis.close(); 

28 } catch (IOException e) { 

29 e.printStackTrace(); 

30

31

32 }

當我們在前端請求這個地址時,伺服器先找出檔案,設定回應標頭,然後通過流輸出到瀏覽器端。

瀏覽器在頭中發現該響應的主體是流檔案,則自動會調用另存新檔的視窗,讓使用者儲存下載。

這裡有個關鍵就是Content-Disposition這個頭屬性,Content-Disposition是MIME協議的擴充,用於指示如何讓用戶端顯示附件的檔案。

它可以設定為兩個值:

inline //線上開啟

attachment //作為附件下載

這裡我們設定的值為attachment,所以可以被識別為附件並下載。

上面講了如何寫伺服器端,下面講前端如何請求。

前端請求有三種方式:

1.Form

1 <form action='download.html' method='post'> 

2 <input type='submit'/> 

3 </form>

2.iframe

1 var iframe = "<iframe style='display:none' src='download.html'></iframe>" 

2 body.append(iframe);

​當iframe被append到body中時,會自動請求下載連結。

3.open

1 window.open("download.html");

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.