下载图片

export function onPostDownload(url, name) {
  axios({
    url: "/file/api/v1/site/download",
    method: "post",
    data: {
      siteFileUrls: [url]
    },
    responseType: "blob",
    headers: {
      token: getToken()
    }
  })
    .then(res => {
      f(res, name);
    })
    .catch(err => {
      console.log("error log --> ", err);
    });
}
const f = (res, name) => {
  if (res.data) {
    const rspHeaders = res.headers;
    const blob = new Blob([res.data], { type: "application/octet-stream" });
    const link = document.createElement("a");
    link.href = URL.createObjectURL(blob);
    document.body.appendChild(link);
    if (rspHeaders["content-disposition"]) {
      try {
        const fileName = decodeURI(
          rspHeaders["content-disposition"]
            .split(";")[1]
            .split("=")[1]
            .replaceAll('"', "")
        );
        const fileNameArr = fileName.split(".");
        link.download = name + "." + fileNameArr[1];
        link.click();
        URL.revokeObjectURL(link.href);
        document.body.removeChild(link);
      } catch (err) {
        console.log("error log --> ", err);
      }
    } else {
      notification.error({ message: "下载失败" });
    }
  }
};

 

posted on 2022-02-23 09:37  阿政kris*  阅读(110)  评论(0编辑  收藏  举报