Cirry's Blog

前端使用js直接下载图片、pdf等等

2023-02-17
技术
js
最后更新:2024-04-24
1分钟
195字

前端直接下载图片和PDF文件的方案,现在很多浏览器都会拦截图片和pdf直接预览,使用流下载的方式可以跳过浏览器的拦截直接下载。

这里提供一个方法,传入文件名和下载地址就可以了,如果后端直接返回流或者直接返回图片,都会直接下载。

1
/**
2
* @param url 文件的下载地址
3
* @param filename 下载下来的文件名
4
*/
5
handleLink(url, filename) {
6
fetch(url, {
7
method: 'get',
8
responseType: 'arraybuffer',
9
}).then((res) => {
10
return res.arrayBuffer()
11
}).then((blobRes) => {
12
// 生成 Blob 对象,设置 type 等信息
13
const e = new Blob([blobRes], {
14
type: 'application/octet-stream',
15
'Content-Disposition': 'attachment'
12 collapsed lines
16
})
17
// 将 Blob 对象转为 url
18
const link = window.URL.createObjectURL(e)
19
// 创建 a 标签
20
let a = document.createElement('a');
21
a.href = link;
22
a.download = filename;
23
a.click();
24
}).catch(err => {
25
console.error(err)
26
})
27
}
本文标题:前端使用js直接下载图片、pdf等等
文章作者:Cirry
发布时间:2023-02-17
版权声明:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
感谢大佬送来的咖啡☕
alipayQRCode
wechatQRCode