根据dataurl下载文件

// 调用接口,下载
。。。.then(res=> {
                    let fileBody = res.fileBody;
                    let fileName = res.fileName;
                    let fileType = res.fileType;
                    let myBlob = dataURLtoBlob(fileBody, fileType);
                    downloadFile(myBlob, fileName, fileType);
})
// 换成成blob
function dataURLtoBlob (dataurl, fileType) {
    // let arr = dataurl.split(",");
    // let mime = arr[0].match(/:(.*?);/)[1];
    let bstr = atob(dataurl);
    let n = bstr.length;
    let u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: fileType });
}
/**
  * 下载文件
  * @param  data 数据流
  * @param  fileName 文件名
  */
function downloadFile(data, fileName = "", SuffixName = 'xlsx') {
    // if (data.data.type == "application/json" || data.data.type == "text/html;charset=utf-8") {
    //   let reader = new FileReader();
    //   reader.readAsText(data.data);
    //   reader.onload = function (res) {
    //     iView.Notice.error({
    //       title: '操作失败',
    //       desc: JSON.parse(res.target.result).message,
    //       duration: 0
    //     })
    //   }
    // }
    // else {
    const blob = new Blob([data]);
    const name = `${fileName}.${SuffixName}`
    if ('msSaveOrOpenBlob' in navigator) {
        window.navigator.msSaveOrOpenBlob(blob, name);
        return;
    }
    if ('download' in document.createElement('a')) { // 非IE下载
        const elink = document.createElement('a')
        elink.download = name
        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 { // IE10+下载
        navigator.msSaveBlob(blob, name)
    }
    // }
}
posted @ 2022-11-01 14:06  ฅ˙-˙ฅ  阅读(127)  评论(0)    收藏  举报