【SpringBoot】如何在網頁上點鏈接下載文件


簡單來說分兩步:

頁面上寫:

<a href="../download">下載</a>

控制器中寫:

    @RequestMapping("/download")
    public void download(HttpServletResponse response) {
        try {
            // path是指想要下載的文件的路徑
            File file = new File("C:\\hy\\hy.rar");

            // 獲取文件名
            String filename = file.getName();
            // 獲取文件后綴名
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();

            // 將文件寫入輸入流
            FileInputStream fileInputStream = new FileInputStream(file);
            InputStream fis = new BufferedInputStream(fileInputStream);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();

            // 清空response
            response.reset();
            // 設置response的Header
            response.setCharacterEncoding("UTF-8");
            // Content-Disposition的作用:告知瀏覽器以何種方式顯示響應返回的文件,用瀏覽器打開還是以附件的形式下載到本地保存
            // attachment表示以附件方式下載 inline表示在線打開 "Content-Disposition: inline;
            // filename=文件名.mp3"
            // filename表示文件的默認名稱,因為網絡傳輸只支持URL編碼的相關支付,因此需要將文件名URL編碼后進行傳輸,前端收到后需要反編碼才能獲取到真正的名稱
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
            // 告知瀏覽器文件的大小
            response.addHeader("Content-Length", "" + file.length());
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            outputStream.write(buffer);
            outputStream.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

實現效果:

參考資料:

https://www.cnblogs.com/javalinux/p/14807398.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM