javaScript 实现将文件流下载文件保存到本地
# 示例一
const saveFile = (data, name) => {
try {
const urlObject = window.URL || window.webkitURL || window;
const export_blob = new Blob([data]);
const blobUrl = urlObject.createObjectURL(export_blob);
const a = document.createElement('a');
a.style.display = 'none';
a.download = name;
a.href = blobUrl;
a.click()
a.remove();
// a.removeChild(a)
} catch (e) {
notification["error"]({
message: '文件保存出错!'
});
}
}
// 调用方法
saveFile(content,'xxx.xxx'); //xxx.xxx 文件名.扩展名
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 示例二
let params = {
modelId: 1427,
};
this.$axios
.get("/model-manage/genTable/downloadTemplate", {
params,
responseType: "blob",
})
.then((res) => {
let filename = res.headers["content-disposition"].split("=")[1];
if (window.navigator.msSaveOrOpenBlob) {
// 兼容IE10
navigator.msSaveBlob(new Blob([res.data]), filename?filename:`file.zip`);
} else {
let url = window.URL.createObjectURL(
new Blob([res.data], { type: "application/octet-stream" })
);
let link = document.createElement("a");
link.style.display = "none";
link.href = url;
link.setAttribute("download", filename?filename: `file.zip`);
document.body.appendChild(link);
link.click();
link.remove();
}
})
.catch((err) => {});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# 示例三
const saveFile = (data, name) => {
try {
const urlObject = window.URL || window.webkitURL || window;
const export_blob = new Blob([data]);
const blobUrl = urlObject.createObjectURL(export_blob);
const a = document.createElement('a');
a.style.display = 'none';
a.download = name;
a.href = blobUrl;
a.click()
// a.removeChild(a)
} catch (e) {
notification["error"]({
message: '文件保存出错!'
});
}
}
// 调用方法
saveFile(content,'xxx.xxx'); //xxx.xxx 文件名.扩展名
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 示例四
export const exportToFile = (data, name) => {
let urlObject = window.URL || window.webkitURL || window;
let export_blob = new Blob([data]);
let save_link = document.createElementNS("http://www.w3.org/1999/xhtml", "a")
save_link.href = urlObject.createObjectURL(export_blob);
save_link.download = name;
let ev = document.createEvent("MouseEvents");
ev.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
save_link.dispatchEvent(ev);
}
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
上次更新: 2024/01/30, 00:35:17
- 01
- linux 在没有 sudo 权限下安装 Ollama 框架12-23
- 02
- Express 与 vue3 使用 sse 实现消息推送(长连接)12-20