前端基于axios请求下载文件(后端返回Blob文件流)

前端小白第一篇csdn文章就当自己记录学习啦!

我自己遇到的情况写在前面防止有人和我不一样,浪费时间浏览;

调用下载接口后端给我返回的数据格式(即文件流格式)如下:

1.按钮定义点击事件

2.调用后端接口

在使用 axios 请求下载文件 api 接口时,注意区分不同请求方法的使用,语法如下:

// axios设置reponseType的方式应该类似下面
const url = '/info/download'
 
// get、delete、head 等请求
axios.get(url, {params: {}, responseType: 'blob'})
    .then((res) => {})
    .catch((err) => {})
 
// post、put、patch 等请求
axios.post(url, {...params}, {responseType: 'blob'})
    .then((res) => {})
    .catch((err) => {})

3.具体实现代码如下(可直接复制粘贴):

注:service是封装了axios

 download() {

      service({

        method: "get",

        url: `后端提供的接口`,

        responseType: "blob",

      }).then((res) => {

        console.log(res);

        console.log(res.data.type);

        let blob = new Blob([res.data], { type: res.data.type });

        let url = window.URL.createObjectURL(blob);

        console.log(url);

        let link = document.createElement("a");

        link.style.display = "none";

        link.href = url;

        link.setAttribute("download", "文件名+后缀");//文件名后缀记得添加,我写的zip

        document.body.appendChild(link);

        link.click();

        document.body.removeChild(link);//下载完成移除元素

        window.URL.revokeObjectURL(url);//释放掉blob对象

猜你喜欢

转载自blog.csdn.net/m0_61676604/article/details/129880068