又做了一个图片下载的功能,下面是代码
download(row) {
this.id = row.id;
const id = this.id;
fetch("URL", { // 这里写下载请求的URL地址
method: "GET",
headers: {
"Content-Type": "application/json",
},
params: {
id: id,
},
})
.then((response) => response.blob())
.then((blob) => {
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = "query_result.json";
a.click();
URL.revokeObjectURL(url);
})
.catch((error) => console.error("下载失败", error));
},
<template slot-scope="scope">
<el-button size="mini" type="text" icon="el-icon-edit" @click="download(scope.row)">下载</el-button>
<template>
-
将传入的
row.id
赋值给本地变量id
和this.id
,以确保在请求发送后id
的值不会改变。 -
使用Fetch API发送GET请求到你的URL地址,并设置请求头的
Content-Type
为application/json
。params
字段在Fetch API中无效,你需要将id
作为查询参数拼接在URL中。 -
在链式调用中,首先将响应转换为Blob对象。
-
将Blob数据转换为URL链接。
-
创建一个a标签,并设置链接(
href
)和下载(download
)属性。 -
将a标签添加到文档中。
-
调用
a.click()
模拟点击a标签,从而触发文件下载。 -
最后通过
URL.revokeObjectURL(url)
释放URL对象,避免内存泄漏。