从接口中获取到pdf的url,前台实现下载功能

思路:使用get请求获取到一个二进制流,然后转为Blob,再通过window.URL.createObjectURL()创建一个 DOMString,赋值给a标签的href,
具体实现如下:
步骤一:get请求该pdf路径,因为blob需要一个二进制流

/*
    url: "http://124.127.246.224:9000/images/2022/10/17/c24f8fd7d53.pdf"
    options: {title:"",fileType:"application/pdf"}
    ele: a标签
*/
let getFile = (url, options, ele) => {
    axios.get(url,{ responseType: 'blob' }).then(res => download(res, options, ele))
}

步骤二:将返回的数据转为Blob

let download = (res, options, ele) => {
    let blob = new Blob([res.data], { type: options.fileType ? options.fileType : "application/octet-binary" });
    let href = window.URL.createObjectURL(blob);
    downloadBlob(href, options, ele);
}

步骤三:执行下载
此处的坑:如果不加ele.click(),需要再次点击才会下载文件,如果加了click自调用,会下载两次,因此使用flag做记录

let flag = 1;
let downloadBlob = (blobUrl, options, ele) => {
    ele.href = blobUrl;
    ele.download = options.title;
    flag++;
    if ((flag % 2) == 0) {
        ele.click();
        window.URL.revokeObjectURL(blobUrl);//释放
    }
}

步骤四:在vue文件中调用

 <el-button type="primary"  @click="download(ele, index)">下载
     <a :id="'d' + index"></a>
 </el-button>

import {getFile} from "@/utils/download"

download(data, index) {
  let arr = data.url.split(".");
  let options = {
    title: data.title,
    fileType: "application/"+arr[arr.length-1]
  };
  let link = document.getElementById("d" + index);
  getFile(data.url,options,link)
},

完整的js文件内容如下:

//download.js
import axios from "axios"  //需要单独引入,因为当前.js文件不会被vue管理
axios.defaults.headers['Cache-Control'] = 'no-cache'
/*
    url: "http://124.127.246.224:9000/images/2022/10/17/c24f8fd7d53.pdf"
    options: {title:"",fileType:"application/pdf"}
    ele: a标签
*/
let getFile = (url, options, ele) => {
    axios.get(url, { responseType: 'blob' }).then(res => download(res, options, ele))
}

let download = (res, options, ele) => {
    let blob = new Blob([res.data], { type: options.fileType ? options.fileType : "application/octet-binary" });
    let href = window.URL.createObjectURL(blob);
    downloadBlob(href, options, ele);
}

let flag = 1;
let downloadBlob = (blobUrl, options, ele) => {
    ele.href = blobUrl;
    ele.download = options.title;
    flag++;
    if ((flag % 2) == 0) {
        ele.click();
        window.URL.revokeObjectURL(blobUrl);
    }
}

export {
    getFile,
    download,
    downloadBlob
}

如果有更好的写法,非常欢迎指正,谢谢~

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐