美文网首页
axios完成下载

axios完成下载

作者: 糖小羊儿 | 来源:发表于2021-03-12 15:18 被阅读0次
import Axios from "axios";
import qs from "qs";
let http = Axios.create({
    headers: {
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
    },
});
//发起下载请求
function downloadPost(url = '', data = {}) {
    let loading = Loading.service({
        lock: true,
        text: "下载中....",
        spinner: "el-icon-loading",
        background: "rgba(255,255,255,0)",
        customClass: "loadingMask",
    });
    return http({
        url,
        data,
        responseType: 'blob',
        method: "post",
        timeout: 600000,
    }).then((res) => {
        loading.close();
        return res;
    });
}
//下载 注意服务器接口返回的请求头里面需要有content-disposition字段
function downloadFile(res) {
    let header_file = res.headers["content-disposition"];
    if (!header_file) {
        return false;
    }
    let fileName = header_file.split(";")[1].split("filename=")[1];
    fileName = decodeURI(fileName);
    let content = res.data;
    let blob = new Blob([content]);
    if ("download" in document.createElement("a")) {
        // 非IE下载
        let elink = document.createElement("a");
        elink.download = 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 {
        // IE10+下载
        navigator.msSaveBlob(blob, fileName);
    }
    return true;
}

this.uploadPost('', {}).then(res => {
    this.downloadFile(res);
});

相关文章

网友评论

      本文标题:axios完成下载

      本文链接:https://www.haomeiwen.com/subject/odszqltx.html