在web開(kāi)發(fā)中,經(jīng)常需要開(kāi)發(fā)“下載”這一模塊,以下給出一個(gè)簡(jiǎn)單的例子。
在服務(wù)器端,使用java開(kāi)發(fā):
view sourceprint?
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 }
當(dāng)我們?cè)谇岸苏?qǐng)求這個(gè)地址時(shí),服務(wù)器先找出文件,設(shè)置響應(yīng)頭,然后通過(guò)流輸出到瀏覽器端。
瀏覽器在頭中發(fā)現(xiàn)該響應(yīng)的主體是流文件,則自動(dòng)會(huì)調(diào)用另存為的窗口,讓用戶(hù)保存下載。
這里有個(gè)關(guān)鍵就是Content-Disposition這個(gè)頭屬性,Content-Disposition是MIME協(xié)議的擴(kuò)展,用于指示如何讓客戶(hù)端顯示附件的文件。
它可以設(shè)置為兩個(gè)值:
inline //在線打開(kāi)
attachment //作為附件下載
這里我們?cè)O(shè)置的值為attachment,所以可以被識(shí)別為附件并下載。
上面講了如何寫(xiě)服務(wù)器端,下面講前端如何請(qǐng)求。
前端請(qǐng)求有三種方式:
1.Form
view sourceprint?1 <form action='download.html' method='post'>
2 <input type='submit'/>
3 </form>
2.iframe
view sourceprint?1 var iframe = "<iframe style='display:none' src='download.html'></iframe>"
2 body.append(iframe);
當(dāng)iframe被append到body中時(shí),會(huì)自動(dòng)請(qǐng)求下載鏈接。
3.open
view sourceprint?1 window.open("download.html");
更多信息請(qǐng)查看IT技術(shù)專(zhuān)欄