后端返回数据流,下载文件

更新:

下载方式比较

也可看看

 

下载的三种方式

以防链接丢失

复制代码

axios.post(url, param, {
  responseType: 'blob'
}).then((res) => {
  console.log('res', res);
  const blob = res.data;
  const reader = new FileReader();
  reader.readAsDataURL(blob);
  reader.onload = (e) => {
    const a = document.createElement('a');
    a.download = `文件名称.zip`;
    // 后端设置的文件名称在res.headers的 "content-disposition": "form-data; name=\"attachment\"; filename=\"20181211191944.zip\"",
    a.href = e.target.result;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
  };
}).catch((err) => {
  console.log(err.message);
});
复制代码

第二种方法:

复制代码
const postDownloadFile = (action, param) => {
    const form = document.createElement('form');
    form.action = action;
    form.method = 'post';
    form.target = 'blank';
    Object.keys(param).forEach((item) => {
        const input = document.createElement('input');
        input.type = 'hidden';
        input.name = item;
        input.value = param[item];
        form.appendChild(input);
    });
    document.body.appendChild(form);
    form.submit();
    document.body.removeChild(form);
}

postDownloadFile(url, param);
复制代码

第三种,

window.open(`${url}?${qs.stringify(param)}`, '_blank');

或者:
  window.location.href = url

 另一种方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
this.$axios
  .post(url接口地址, params请求参数, {
    headers: {
      token: token
    },
    responseType: "arraybuffer"
  })
  .then((file) => {
    let content = file.data;
    // 组装a标签
    let elink = document.createElement("a");
    // 设置下载文件名
    elink.download = "附件.zip";
    elink.style.display = "none";
    let blob = new Blob([content], {type: "application/zip"})
    elink.href = URL.createObjectURL(blob);
    document.body.appendChild(elink);
    elink.click();
    document.body.removeChild(elink);
  })

  或者:

 

posted @   everseven  阅读(467)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示