methods: { getfile() { this.ylLoading = true; const userReqData = { contractNum: this.formObj.contractNum } crudBilling.getfile(userReqData).then(res => { this.ylLoading = false; let blob = new Blob([res], { type: 'application/pdf' // 后台返回 pdf 类型的文件,如果是其他文件,可以根据MIME表来选择对应的文件类型 }) let fileName = Date.parse(new Date()) + '.pdf' if (window.navigator.msSaveOrOpenBlob) { navigator.msSaveBlob(blob, fileName) } else { var link = document.createElement('a') link.href = window.URL.createObjectURL(blob) link.download = fileName //打开新的标签页,渲染pdf文件 window.open(link) //释放内存,使的链接只能打开一次。保证安全性。 window.URL.revokeObjectURL(link.href) } }).catch(message => { this.ylLoading = false; }); } }springboot接口代码
@NeedLog @GetMapping("/getFile") @PreAuthorize("@el.check('contract:getFile')") public void getFile(@RequestParam Long id,HttpServletResponse response)throws Exception{ contractService.getFile(id,response); }
@Override public void getFile(Long id, HttpServletResponse response) throws Exception { Contract contract = contractRepository.findById(id); if (contract == null) { return; } String url = contract.getUrl(); File file = new File(url); if (file.exists()) { response.addHeader("Content-Disposition", "inline;fileName=" + java.net.URLEncoder.encode(file.getName(), "UTF-8")); response.setContentType("application/octet-stream;"); response.setHeader("Content-Length",""+file.length()); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); byte[] buff = new byte[1024]; OutputStream os = response.getOutputStream(); try { int i; while ((i = bis.read(buff)) != -1) { os.write(buff, 0, i); } } catch (IOException e) { log.error("下载pdf异常", e); } finally { os.flush(); os.close(); } } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)