背景:已知Java拿到了一个PDF链接(http://xxx.xxx.pdf),直接把链接返给前端的话,前端是不能点击直接下载的,需要后端先把url转成文件流,再由前端下载,处理如下:
导入pom:
<dependency><groupId>org.apache.pdfbox</groupId><artifactId>pdfbox</artifactId><version>2.0.24</version></dependency>
接口部分:
@GetMapping("/downloadPdf")publicvoiddownloadPdf(@RequestParamString patentId,HttpServletResponse response)throwsIOException{String pdfLink ="http://xxx.xxx.pdf";URL url =newURL(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);}}}
前端部分:
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 =newBlob([response.data]);const url =URL.createObjectURL(blob);const link = document.createElement('a');
link.href = url;
link.download =`xxx.pdf`;// 下载的文件名字
link.click();});}
这样前端一点击,就能直接下载。
以上只适用于PDF,如下方式更万金油:
URL url =newURL(fileSrcUrl);HttpURLConnection connection =(HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();InputStream inputStream =newBufferedInputStream(connection.getInputStream());ByteArrayOutputStream outputStream =newByteArrayOutputStream();byte[] buffer =newbyte[1024];int bytesRead;while((bytesRead = inputStream.read(buffer))!=-1){
outputStream.write(buffer,0, bytesRead);}byte[] fileBytes = outputStream.toByteArray();String fileName = url.getFile().substring(url.getFile().lastIndexOf('/')+1);HttpHeaders headers =newHttpHeaders();
headers.add("Content-Disposition","attachment; filename="+ fileName);returnnewResponseEntity<>(fileBytes, headers,HttpStatus.OK);
前端轮询下载结果:
downloadFile(){
let url =this.baseUrl +"/baidu-translate/status?requestId="+this.requestId;axios({
method:'get',
url: url,
responseType:'blob',
headers:{'Authorization':'Bearer '+getToken()}}).then(res =>{
console.log(res)if(res.status ===201){
console.log('等待两秒再重试')setTimeout(this.downloadFile,3*1000);}else{// 文件下载const blob =newBlob([res.data],{
type:'application'})// 获得文件名称
let link = document.createElement('a')
link.download =this.fileName
link.style.display ='none'
link.href = URL.createObjectURL(blob)
document.body.appendChild(link)
link.setAttribute('download',this.fileName)
link.click()
URL.revokeObjectURL(link.href);
document.body.removeChild(link);
link =null;this.loading =false}}).catch(err =>{
console.log(err)this.$message.error('翻译失败,请稍后再试');this.loading =false})}
版权归原作者 电脑令人发狂的 所有, 如有侵权,请联系我们删除。