js下载文件

1.返回下载链接的:

const a = document.createElement('a');
const url = "下载链接";
a.href = url;
a.download = "文件名称.格式";
a.click();
window.URL.revokeObjectURL(url);

2.blob方式下载:

// res为返回的blob格式数据
function download(res) {
    // 错误处理
    if (res.data.type == "application/json") {
        let reader = new FileReader();
        reader.readAsText(res.data, 'utf-8');
        reader.onload = function() {
            let json_data = JSON.parse(reader.result);
            // json_data.Message: 错误信息
        }
        return;
    }
    // 下载处理
    let filename = "content-disposition" in res.headers ?
        decodeURIComponent(
            res.headers["content-disposition"]
            .split(";")[1]
            .split("=")[1]
            .replace(/"/g, "")
        ) :
        "下载文件";
    try {
        if (window.navigator.msSaveOrOpenBlob) {
            navigator.msSaveBlob(res.data, filename);
        } else {
            let blob = new Blob([res.data], {
                type: "application/vnd.ms-excel"
            });
            let url = URL.createObjectURL(blob);
            let link = document.createElement("a");
            link.setAttribute("href", url);
            link.setAttribute("download", filename);
            link.style.display = "none";
            document.body.appendChild(link);
            link.click();
            URL.revokeObjectURL(url); // 释放URL 对象
            document.body.removeChild(link);
        }
    } catch (err) {
        // console.log(err)
    }
}

 

你可能感兴趣的:(js下载文件)