vue和springmvc下载文件亲测的两种方式
第一种:responseType: 'blob' ,这种方式用于文件在磁盘中
vue:
download(index,row){ var ts = this; axios.post(this.paths.baseURL+'file/downloadFile', {path:row.zurl}, {responseType: 'blob'} ).then(msg => { let link = document.createElement("a"); link.style.display = "none"; link.href = window.URL.createObjectURL(new Blob([msg.data])); link.setAttribute("download",row.zurl.substring(row.zurl.lastIndexOf("/")+1));//文件名 document.body.appendChild(link); link.click(); URL.revokeObjectURL(link.href); document.body.removeChild(link); }).catch(error =>{ ts.$message.error('下载文件失败') }) },
java:
@RequestMapping(value = "downloadFile",method = RequestMethod.POST,produces = {"application/json;charset = utf-8"}) @ApiOperation(notes = "下载",value = "下载") @RequiresPermissions("file:download") public ResponseEntity<byte[]> downloadFile(@RequestBody Map<String,Object> map) throws IOException { String path = map.get("path").toString(); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); headers.setContentDispositionFormData("attachment", path.substring(path.lastIndexOf("/") + 1)); return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(new File(path)), headers, HttpStatus.CREATED); }
第二种:这种方式用于文件在项目中
vue:
download(){ window.open(this.paths.baseURL+'risk/downloadRisk') },
java:
@ApiOperation(notes = "下载",value = "下载") @GetMapping(value = "downloadRisk") // @RequiresPermissions("risk:download") public void downloadRisk(HttpServletResponse response) throws IOException { try { String path = System.getProperty("user.dir")+"\\trunk\\src\\main\\resources\\excelTemplate\\dowload\\风险辨识模板.doc"; File file = new File(path); InputStream fis; fis = new BufferedInputStream(new FileInputStream(path)); byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); response.reset(); String fileName = URLEncoder.encode("风险数据模板报告.doc","UTF-8"); response.addHeader("Content-Disposition", "attachment;filename=" + fileName); 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(); } }