首頁  >  文章  >  web前端  >  java、javascript實作附件下載範例_javascript技巧

java、javascript實作附件下載範例_javascript技巧

WBOY
WBOY原創
2016-05-16 16:39:321297瀏覽

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

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

@RequestMapping(value = "download.html", method = RequestMethod.GET) 
public void download(String resourceid, HttpServletRequest request, HttpServletResponse response) { 
response.setContentType("charset=UTF-8"); 
File file = new File(path); 
response.setHeader("Content-Disposition", "attachment; filename=a"); 
BufferedInputStream bis = null; 
BufferedOutputStream bos = null; 
OutputStream fos = null; 
InputStream fis = null; 
try { 
fis = new FileInputStream(file.getAbsolutePath()); 
bis = new BufferedInputStream(fis); 
fos = response.getOutputStream(); 
bos = new BufferedOutputStream(fos); 
int bytesRead = 0; 
byte[] buffer = new byte[5 * 1024]; 
while ((bytesRead = bis.read(buffer)) != -1) { 
bos.write(buffer, 0, bytesRead); 
} 
bos.flush(); 
}catch(E e){ 
}finally { 
try { 
bis.close(); 
bos.close(); 
fos.close(); 
fis.close(); 
} catch (IOException e) { 
e.printStackTrace(); 
} 
} 
}

當我們在前端請求這個位址時,伺服器先找出文件,設定回應頭,然後透過串流輸出到瀏覽器端。

瀏覽器在頭中發現該回應的主體是串流文件,則自動會呼叫另存為的窗口,讓使用者儲存下載。

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

它可以設定為兩個值:

inline //線上開啟

attachment //作為附件下載

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

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

前端請求有三種方式:

1.Form

<form action='download.html' method='post'> 
<input type='submit'/> 
</form>

2.iframe

var iframe = "<iframe style='display:none' src='download.html'></iframe>" 
body.append(iframe);

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

3.open

window.open("download.html");

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn