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; |
| 11 |
fis = new FileInputStream(file.getAbsolutePath()); |
| 12 |
bis = new BufferedInputStream(fis); |
| 13 |
fos = response.getOutputStream(); |
| 14 |
bos = new BufferedOutputStream(fos); |
| 16 |
byte[] buffer = new byte[5 * 1024]; |
| 17 |
while ((bytesRead = bis.read(buffer)) != -1) { |
| 18 |
bos.write(buffer, 0, bytesRead); |
| 28 |
} catch (IOException e) { |
當我們在前端請求這個地址時,伺服器先找出檔案,設定回應標頭,然後通過流輸出到瀏覽器端。
瀏覽器在頭中發現該響應的主體是流檔案,則自動會調用另存新檔的視窗,讓使用者儲存下載。
這裡有個關鍵就是Content-Disposition這個頭屬性,Content-Disposition是MIME協議的擴充,用於指示如何讓用戶端顯示附件的檔案。
它可以設定為兩個值:
inline //線上開啟
attachment //作為附件下載
這裡我們設定的值為attachment,所以可以被識別為附件並下載。
上面講了如何寫伺服器端,下面講前端如何請求。
前端請求有三種方式:
1.Form
| 1 |
<form action='download.html' method='post'> |
2.iframe
| 1 |
var iframe = "<iframe style='display:none' src='download.html'></iframe>" |
當iframe被append到body中時,會自動請求下載連結。
3.open
| 1 |
window.open("download.html"); |