axios+post下载文件

遇到一个需求是,选择区域的站点之后,用get请求,站点ID的数组参数可能会超过浏览器参数长度限制,最后无法下载。于是换成了post方式下载文件。

第一步:与后台沟通好response header的设置,并规定好fileName的编码方式,方便前端拿到后解析

content-disposition: attachment;fileName=%E9%81%A5%E6%84%9F%E8%A7%A3%E8%AF%91%E6%95%B0%E6%8D%AE.xls
content-type: application/octet-stream

第二步:设置axios的responseType为blob

axios({
  method: 'post',
  url: 'xxx/xxx',
  data: { ids: [1,2,3]},
  responseType: 'blob'
}).then(response => {
  this.exportFile(response)
}).catch((error) => {
    console.log(error)
})

第三步:拿到文件流后实现下载

exportFile(result){
    const contentDisposition = result.headers['content-disposition'];
    const filename = decodeURI(contentDisposition.split('fileName=')[1] || contentDisposition.split('filename=')[1]);
    const blob = new Blob([result.data]);
    const url = window.URL.createObjectURL(blob);
    if (window.navigator.msSaveBlob) {
        try {
            window.navigator.msSaveBlob(blob, filename);
        }
        catch (e) {
            console.log(e);
        }
    }
    else {

        let link = document.createElement('a');
        link.style.display = 'none';
        link.href = url;
        link.setAttribute('download', filename);
        document.body.appendChild(link);
        link.click();
    }
}
发布了45 篇原创文章 · 获赞 15 · 访问量 13万+

猜你喜欢

转载自blog.csdn.net/qq_39364032/article/details/103010663