Axios实现excel表格下载

    Axios({
            url: 'url',
            method: 'post',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            transformRequest: [function (data) {//请求发起前进行参数拼接(非必须,根据实际情况考虑)
                let ret = '';
                for (let it in data) {
                    if (it) {
                        ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&';
                    }
                }
                return ret;
            }],
            data: data,
            withCredentials: true,
            responseType: 'blob'// 返回的数据格式,必填,不然会返回乱码
        }).then((resp) => {
            console.log(resp);
            let href = window.URL.createObjectURL(new Blob([resp.data]));
            let link = document.createElement('a');
            let fileName = decodeURI(resp.headers['content-disposition'].split('filename =')[1]);
            link.style.display = 'none';
            link.href = href;
            link.setAttribute('download', fileName);

            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            window.URL.revokeObjectURL(href);
        });

  

posted @ 2020-09-28 09:46  至善为止  阅读(146)  评论(0编辑  收藏  举报