簡單來說分兩步:
頁面上寫:
<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(); } }
實現效果:
參考資料: