JS-a标签下载文件

wujiawen 发布于

a标签下载文件

当下载文件中存在jpg、txt等浏览器可以直接预览的文件,使用a标签即使加了download仍然会在浏览器中打开下载文件

1
<a href="" download=""></a>

经过尝试,当需要下载的是图片时,通过canvas将图片转为blob数据,再获取blob地址,然后进行下载

当下载excel等文件时,可直接下载

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
32
33
34
35
36
37
38
39
40
41
42
43
44
/**
* 附件下载 图片与其他文件分开下载 图片直接用a标签会预览 要先转blob再下载
* @param {String} url
* @param {String} name
*/
export function downloadFile (url, name = '') {
if (!url) return
const pictureList = ['jpg', 'gif', 'png']
const enclosures = url.split('/')
// 这里的图片名称按实际情况而定 我这里是因为url中带有文件名
// 若url不带文件名,就传入文件名(需要后缀,用以判断文件类型)
const originName = enclosures[enclosures.length - 1]
if (pictureList.includes(originName.split('.')[originName.split('.').length - 1])) {
downloadPicture(url, name)
return
}
const a = document.createElement('a')
const event = new MouseEvent('click')
a.download = name || originName
a.href = url
a.dispatchEvent(event)
}
function downloadPicture (url, name) {
const enclosures = url.split('/')
const originName = enclosures[enclosures.length - 1]
let suffix = originName.split('.')[originName.split('.').length - 1]
if (suffix === 'jpg') suffix = 'jpeg'
const image = new Image()
image.setAttribute('crossOrigin', 'anonymous')
image.src = url
image.onload = function () {
const canvas = document.createElement('canvas')
canvas.width = image.width
canvas.height = image.height
const context = canvas.getContext('2d')
context.drawImage(image, 0, 0, image.width, image.height)
const downloadUrl = canvas.toDataURL(`image/${suffix}`)
const a = document.createElement('a')
const event = new MouseEvent('click')
a.download = name || originName
a.href = downloadUrl
a.dispatchEvent(event)
}
}