java、javascript實現(xiàn)附件下載示例

字號:


    在web開發(fā)中,經(jīng)常需要開發(fā)“下載”這一模塊,以下給出一個簡單的例子。
    在服務(wù)器端,使用java開發(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)我們在前端請求這個地址時,服務(wù)器先找出文件,設(shè)置響應(yīng)頭,然后通過流輸出到瀏覽器端。
    瀏覽器在頭中發(fā)現(xiàn)該響應(yīng)的主體是流文件,則自動會調(diào)用另存為的窗口,讓用戶保存下載。
    這里有個關(guān)鍵就是Content-Disposition這個頭屬性,Content-Disposition是MIME協(xié)議的擴展,用于指示如何讓客戶端顯示附件的文件。
    它可以設(shè)置為兩個值:
    inline //在線打開
    attachment //作為附件下載
    這里我們設(shè)置的值為attachment,所以可以被識別為附件并下載。
    上面講了如何寫服務(wù)器端,下面講前端如何請求。
    前端請求有三種方式:
    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中時,會自動請求下載鏈接。
    3.open
    view sourceprint?1 window.open("download.html");