axios 请求下载文件

 

import axios from 'axios'; 
axios.post(url, { ...getDataDefault(), reqBody: { ...params }, }, { responseType: 'blob' })
        .then(function (response) {
            const { data } = response
            let type = data.type
            const relType = ['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']
            if (type.includes('application/json')) {
                let reader = new FileReader()
                reader.onload = function (event) {
                    let content = reader.result
                    let message = JSON.parse(content).message // 错误信息
                    // TODO 错误处理
                }
                reader.readAsText(data)
                return true
            } else if (relType.includes(type)) {
                var blob = new Blob([data])
                var downloadElement = document.createElement('a');
                var href = window.URL.createObjectURL(blob); //创建下载的链接
                downloadElement.href = href;
                downloadElement.download = `${name}.xlsx`; //下载后文件名
                document.body.appendChild(downloadElement);
                downloadElement.click(); //点击下载
                document.body.removeChild(downloadElement); //下载完成移除元素
                window.URL.revokeObjectURL(href); //释放掉blob对象 
            }
        })
        .catch(function (error) {
            console.log(error);
        });

 

上一篇:vue导出Excel


下一篇:在vue中实现axios异步下载(vue-cli,脚手架)