关于文件下载的封装

import axios from 'axios'
const isIE = () => navigator.userAgent.toLowerCase().indexOf('trident') > -1;  //判断是否为IE浏览器
// 文件下载
export async function downLoad(params) {
    // return request('/ability/api/rs/gw/file/' + params.id, {
    //     method: 'get',
    // })
    return axios({ // 用axios发送post请求
        method: 'get',
        url: '/ability/api/rs/gw/file/' + params.id,
        // url: `/api/v4/idc_settlement/${data.tag}/exportExcel`, // 请求地址
        data: {}, // 参数
        responseType: 'blob', // 表明返回服务器返回的数据类型
        headers: {
            'Content-Type': 'application/json',
            'token': token,
            'Authorization': token
        }
    }).then(res => {
        console.log(res);
        // if (res.data.type == 'application/vnd.ms-excel' || res.data.type == 'application/vnd.ms-excel;charset=UTF-8') {
        //     const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' });
        //     const fileName = decodeURI(res.headers['content-disposition'].split('filename=')[1]);
        if (res.status == 200) {
            const fileName = params.name;
            const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' });
            if (isIE()) {
                window.navigator.msSaveOrOpenBlob(blob, fileName);
                // message.success('导出成功');
            } else {
                const elink = document.createElement('a');
                elink.id = 'testPrint1'
                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);
                // message.success('导出成功');
            }
        } else {
            message.error('导出失败,请查看是否存在数据')
        }

        // } else {
        //     message.error('导出失败,请查看是否存在数据')
        // }
    })

    // .catch(err => {
    //     message.error('导出失败')
    // });
}
posted @ 2023-09-22 14:28  Y~~~  阅读(18)  评论(0)    收藏  举报