背景:已知Java拿到了一个PDF链接(http://xxx.xxx.pdf),直接把链接返给前端的话,前端是不能点击直接下载的,需要后端先把url转成文件流,再由前端下载,处理如下:
导入pom:
<dependency><groupId>org.apache.pdfbox</groupId><artifactId>pdfbox</artifactId><version>2.0.24</version></dependency>
接口部分:
java"> @GetMapping("/downloadPdf")public void downloadPdf(@RequestParam String patentId, HttpServletResponse response) throws IOException {String pdfLink = "http://xxx.xxx.pdf";URL url = new URL(pdfLink);try (InputStream inputStream = url.openStream();PDDocument document = PDDocument.load(inputStream)) {// 设置响应头response.setContentType("application/pdf");response.setHeader("Content-Disposition", "attachment;");// 写入响应流try (OutputStream outputStream = response.getOutputStream()) {document.save(outputStream);}}}
前端部分:
javascript"> downloadPDF() {let url = baseURL + "/xxx/xxx/downloadPdf?patentId=" + this.patent_id; // 对应后端接口console.log(url);axios({method: 'get',url: url,responseType: 'blob', // 不加的话会白页headers: {'Authorization': 'Bearer ' + getToken()}}).then(response => {const blob = new Blob([response.data]);const url = URL.createObjectURL(blob);const link = document.createElement('a');link.href = url;link.download = `xxx.pdf`; // 下载的文件名字link.click();});}
这样前端一点击,就能直接下载。