在web開發中,經常需要開發“下載”這一模塊,以下給出一個簡單的例子。
在服務器端,使用java開發:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
@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
1
2
3
|
< form action = 'download.html' method = 'post' > < input type = 'submit' /> </ form > |
2.iframe
1
2
|
var iframe = "<iframe style='display:none' src='download.html'></iframe>" body.append(iframe); |
?當iframe被append到body中時,會自動請求下載鏈接。
3.open
1
|
window.open( "download.html" ); |