在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");