文件的下载

一、有文件的链接地址
二、通过接口返回文件数据下载
1、以blob类型返回

axios({
    method: "get",
    url:'https://xxx/download',
    responseType: "blob",
    headers: {
      "Content-Type": "application/json",
      token:'test-token'
    },
  })
    .then((res) => {
      console.log(res);
      if (200 == res.status && res.data && res.data instanceof Blob) {
        let docType = res.headers["content-type"];
        let blob = new Blob([res.data], { type: docType });
        //在本地的时候'content-disposition',但是生产或其他环境就是'Content-Disposition'
        let contentDis =
          res.headers["Content-Disposition"] ||
          res.headers["content-disposition"];
        let fileName = contentDis.split("filename=")[1];
        const elink = document.createElement("a");
        elink.download = window.decodeURI(fileName);
        elink.style.display = "none";
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        URL.revokeObjectURL(elink.href); // 释放URL 对象
        document.body.removeChild(elink);
      } else {
        console.error("downloadFile errors!");
      }
    })
    .catch(() => {
      console.error("downloadFile errors!");
    });

你可能感兴趣的:(前端,javascript,json)