前端基于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对象

相关推荐
不可能片场几秒前
工程实践 雪花id进JS别当数字传
前端·electron
涛涛ing7 分钟前
AI帮我生成了一个炫酷的3D大屏,上线3天就卡崩了
前端
jerrywus16 分钟前
用 AMD Radeon Cloud 免费跑 ComfyUI:从开机到打开界面
前端·agent·claude
学以智用18 分钟前
CKEditor5 完整详解
前端·后端
掘金者阿豪26 分钟前
数据库性能优化:一次慢查询背后,可能不只是SQL的问题
前端·后端
deli0072 小时前
锁过期了业务还没跑完:SETNX 分布式锁 1000 次并发实测
前端
不一样的少年_3 小时前
用了这 Skill,我觉得前端兄弟可以毕业了
前端·后端·agent
FRing033 小时前
vue2干货总结10(json-server、vant-ui、postcss插件、axios二次封装、图形验证码、toast轻提示)
开发语言·前端·vue.js·ui·json·vue2·postcss
程序员大阳3 小时前
副队长ES6+教程(5)--模板字符串
javascript·vue.js·es6·模板字符串
梦想很大很大3 小时前
一句“你好”用了 5671 Token:我在 Workrun 中追查 Agent 隐性成本的过程
前端·人工智能·后端