一,实现目的,后台写一个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 οnclick="download()"></button>
转载于:https://www.cnblogs.com/lovefaner/p/10071801.html