vue axios 导出功能

版权声明:本文为博主原创文章,转载请注明出处 thx~ https://blog.csdn.net/x550392236/article/details/89516834
  1. 请求后台接口
  2. 后台返回二进制流
  3. 前端实现浏览器自动下载成exlce文件

如下图:
在这里插入图片描述
主要方法如下:

/**
 * download方法
 * @param {String} type [请求的方式]
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 * @param {String} fileType [导出文件类型] 默认值 xls
 * @param {String} fileName [导出文件名称] 默认值 导出文件
 */
function download(url, params, fileType, fileName) {
    fileType = fileType || 'xls';
    fileName = fileName || '导出文件';
    let config = {
        params: params,
        // headers和responseType一定要在一起设置,否则会导致 获取到的二进制文件流 格式不正确
        headers: {
            'content-disposition': "attachment;filename=total." + fileType,
            'Content-Type': 'application/x-download;charset=utf-8'
        },
        responseType: 'blob' // 设置请求数据格式
    };
    return new Promise((resolve, reject) => {
        axios.get(url, config)
            .then(err => {
                resolve(err.data);
                if (!err) {
                    return
                }
                let url = window.URL.createObjectURL(err.data);
                let link = document.createElement('a');
                link.style.display = 'none';
                link.href = url;
                link.setAttribute('download', `${fileName}.${fileType}`);
                document.body.appendChild(link);
                link.click();
            })
            .catch(err => {
                reject(err.data);
            })
    });
}

export default {
    download
}

调用

// 导出
exportBtn() {
	this.axios.download(`/api/common-service/export`);
}

猜你喜欢

转载自blog.csdn.net/x550392236/article/details/89516834
今日推荐