02vue+axios+form實現檔案下載(附Java實現程式碼)

wyfem發表於2021-09-09

1.0前端實現思路

用一個from接收後臺返回的檔案流。form用display為none隱藏;其中form構造action屬性,屬性值為後臺檔案下載的引數。同樣可以用display為none的input插入form中,input可以攜帶引數,後臺可以用@requestParam接收。
前端具體程式碼如下:

<!doctype html><html lang="en"><head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title></head><body>
    <div id="app" class="m-5">
        <input type="button" value="下載" @click="handlerClick">
    </div>
    <script>
        new Vue({                    el: '#app',                    data: {                        files: []
                    },                    methods: {                        handlerClick: function () {                            //自定義form標籤,初始化相關引數 
                            var form = document.createElement("form");                            var access_token = "1756467474";
                            form.setAttribute("style",                                "display:none");
                            form.setAttribute("method", "get");                            var params = {};
                            params.Authorization = access_token;
                            form.setAttribute("header",
                                params);                            var path =                                'E:\_ex_workplace\zxsbWeb\esgov-zxsb-zxsbweb\src\pages\selfDetection.vue';                            var input = document.createElement('input');
                            input.setAttribute('type', 'hidden');
                            input.setAttribute('name', 'path');
                            input.setAttribute('value', path);
                            form.append(input);
                            form.setAttribute("action",                                ""
                            );
                            form.setAttribute("target", "_blank");                            var body = document.createElement("body");
                            body.setAttribute("style", "display:none");                            document.body.appendChild(form);
                            form.submit();
                            form.remove();
                        }
                    }    </script></body></html>

02.java程式碼實現

後端Java程式碼實現首先將檔案讀入到陣列buffer中,然後用response獲取輸出流,輸出流將buffer寫出即可。

@GetMapping("/download")    public void download(@RequestParam("path") String path, HttpServletResponse response) {
        System.out.println(path);        try {            // path是指欲下載的檔案的路徑。
            File file = new File(path);            // 取得檔名。
            String filename = file.getName();            // 取得檔案的字尾名。
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();            // 以流的形式下載檔案。
            InputStream fis;
            fis = new BufferedInputStream(new FileInputStream(path));            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();            // 清空response
            response.reset();            // 設定response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }



作者:exmexm
連結:


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/2894/viewspace-2815498/,如需轉載,請註明出處,否則將追究法律責任。

相關文章