blob - 二进制文件流下载

/**
 * 返回值文件类型为 blob 二进制流文件
 * responseType: 'blob' 
 * params 接口所需参数
 * 命名文件名:依据时间戳命名文件名
 *      (导出时需要延迟,否则导出文件失败,默认文件名时直接导出)
 * */

$axios.get(`api`, {
    responseType: 'blob',
    params
}).then((res) => {
    // response 的返回值为二进制文件流

    // 创建时间戳
    let date = new Date(),
        yyyy = date.getFullYear(),
        MM = date.getMonth() + 1,
        dd = date.getDate(),
        hh = date.getHours(),
        mm = date.getMinutes(),
        ss = date.getSeconds();
    var timeStr = `${yyyy}${MM}${dd}${hh}${mm}${ss}`;

    // 导出二进制文件
    setTimeout(() => {
        // 创建URL对象 URL.createObjectURL(object)
        let url = window.URL.createObjectURL(res.data);
        let link = document.createElement('a');
        link.style.display = 'none';
        link.href = url;
        // 指定文件名&文件类型(后缀名)
        let fileName = `Users${timeStr}CN.xls`;
        /**
         * 添加属性,并赋指定的值 el.setAttribute('download','zzz')
         * demo: <a href="abc.gif" download="zzz"> 
         * download属性的值即使当前要导出的文件的文件名
         * */
        link.setAttribute('download', fileName);
        link.click();
        // 释放创建的对象(创建的新的URL必须通过该方法释放)
        window.URL.revokeObjectURL(url);
    }, 500);
}).catch((err) => {
    console.log('文件导出失败: ', err);
});

猜你喜欢

转载自www.cnblogs.com/zxk5211/p/web_30.html