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

相关推荐
不想上班只想要钱9 分钟前
动态类名在 <swiper-slide 的复制项中没有起作用的解决方法
前端·vue.js
weixin_3954489111 分钟前
tidl_import_mul_rmfsd_psd_u8_3x480x544_bise_raw_dynamic.txt
java·服务器·前端
多多*1 小时前
图解Redis的分布式锁的历程 从单机到集群
java·开发语言·javascript·vue.js·spring·tomcat·maven
Jinuss1 小时前
源码分析之React中updateContainerImpl方法更新容器
前端·react.js·前端框架
Mr Xu_2 小时前
Vue + Element Plus 实现前端导出 Excel 功能详解
前端·javascript·vue.js
前端大波2 小时前
vue3的自动化路由(unplugin-vue-router)
javascript·vue.js·自动化
仰泳之鹅2 小时前
【杂谈】使用Edge浏览器下载文件显示“Microsoft Defender SmartScreen 已阻止此不安全文件”的解决方法
前端·edge
万邦科技Lafite2 小时前
小红书评论数据一键获取,item_reviewAPI接口讲解
大数据·前端·数据库·chrome·电商开放平台
戌中横2 小时前
JavaScript 对象
java·开发语言·javascript
meng半颗糖3 小时前
vue3+tpescript 点击按钮跳转新页面直接通过链接预览word
前端·vue.js·word