学无先后,达者为师

网站首页 Vue 正文

vue使用axios接收流文件的实现_vue.js

作者:weixin_43869439   更新时间: 2022-10-02 Vue

在工作中遇到使用axios接收流文件,遇到了一些问题,整理如下:

在调用接口成功后如图所示:

现在需要调试下axios.js文件统一拦截

// 导出
    const headers = response.headers
    //console.log(headers['content-type'])  将打印的值,也将后台返回的相应头设置成相同的,我的就是'application/octet-stream;charset=UTF-8',然后返回response
    if (headers['content-type'] == 'application/octet-stream;charset=UTF-8') {
        return response;
    }

现在需要注意headers[‘content-type’] 不一定是 ‘application/octet-stream;charset=UTF-8’
在接口调用时需要设置axios的相应类型,responseType: “blob”

this.axios({
   	method: "get",
    url: "/dafw/cljsdc",
    params: data,
    responseType: "blob"
  })
    .then(res => {
    let blob = new Blob([_res]);
    let downloadElement = document.createElement("a");
    let href = window.URL.createObjectURL(blob); //创建下载的链接
    downloadElement.href = href;
    downloadElement.download = "xxx.xls"; //下载后文件名
    document.body.appendChild(downloadElement);
    downloadElement.click(); //点击下载
    document.body.removeChild(downloadElement); //下载完成移除元素
    window.URL.revokeObjectURL(href); //释放掉blob对象
	...

之后就会下载成功…

原文链接:https://blog.csdn.net/weixin_43869439/article/details/100916160

栏目分类
最近更新