一,實現目的,后台寫一個controller,然后前台頁面點擊文件下載,實現文件下載功能。(文件是存放於服務器的磁盤上的)
@RequestMapping("/filesdownloads") public ResponseEntity<byte[]> EIToolDownloads(HttpServletRequest request,HttpServletResponse response) throws IOException{ String doenLoadPath = "xxx"; // doenLoadPath是文件路徑(一般指服務器上的磁盤位置) File file = new File(doenLoadPath); if(file.exists()){ HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); headers.setContentDispositionFormData("attachment", file.getName()); return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers,HttpStatus.OK); }else{ System.out.println("文件不存在,請重試..."); return null; } }
二,前台只需要一個a標簽即可:
HTML代碼:
<a href="/filesdownloads" >下載</a>
三,前台也可以通過點擊button觸發下載功能
//js代碼 function download(){ self.location.href("/filesdownloads"); } //html代碼 <button onclick="download()"></button>