vue文件二进制 下载

  • Post author:
  • Post category:vue


import axios from 'axios';

export function downloadFile(params = {}) {
    const { methods, url, data, headers, responseType, timeout, filename } = params;

    axios.interceptors.request.use(config => {
        config.headers = { ...headers };
        return config;
    }, error => {
        return Promise.reject(error);
    });

    return axios({
        methods: methods,
        url: `${url}`,
        data,
        responseType: responseType || 'blob',
        timeout: timeout || 600000,
    }).then(res => {
        const content = res.data;
        if (res.headers['content-type'] === "application/json;charset=utf-8") {
            const contentBlob = new Blob([content]);
            const fr = new FileReader();
            fr.readAsText(contentBlob, "utf-8");
            fr.onload = () => {
                const res = JSON.parse(fr.result);
                console.log(res);
            }
            return Promise.reject(new Error("error"));
        }

        let fileName = filename || decodeURIComponent(res.headers["content-dispositions"]);
        if (!filename) {
            fileName = fileName.split(";")[1]?.split["="][1]?.replace(/["]/g, '');
        }

        if (window.navigator.msSaveOrOpenBlob) {
            // ie
            try {
                const contentBlob = new Blob([content], { type: res.headers["content-type"] });
                window.navigator.msSaveOrOpenBlob(contentBlob, fileName);
                return Promise.resolve("successful");
            } catch (e) {
                console.log(e);
                return Promise.reject(new Error("error"));
            }
        } else {
            const url = window.URL.createObjectURL(new Blob([content], { type: res.headers["content-type"] }));
            const link = document.createElement("a");
            link.style.display = "none";
            link.href = url;
            link.setAttribute("download", fileName);
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            window.URL.revokeObjectURL(url);
            return Promise.resolve("successful");
        }
    })
}




版权声明:本文为Lixw296182原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。