其他分享
首页 > 其他分享> > axios 请求下载文件

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);
        });

 

标签:axios,请求,downloadElement,let,blob,reader,type,下载
来源: https://blog.csdn.net/bingfenghuiyipp/article/details/113704910