js将base64编码的文件保存为本地图片


最近项目有个需求,需要将后台返回的base64格式的图片文件导出到本地(即点击下载)

开始以为很简单,用a标签的download属性就行了,后来还是出现了很多兼容性问题,不得不重新考虑

但是有一次在看到echarts的demo的时候,它的右上角有个导出按钮(这个功能的兼容性很好),于是决定把其代码扣出来

1543026080(1)

代码如下:

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
function saveAsImg(fileName, url) {
// from echarts
// https://github.com/apache/incubator-echarts/blob/master/src/component/toolbox/feature/SaveAsImage.js
const a = document.createElement('a')
a.download = fileName
a.href = url
const ua = navigator.userAgent
// IE 11 Trident/7.0; rv:11.0
const isIE = ua.match(/MSIE\s([\d.]+)/) || ua.match(/Trident\/.+?rv:(([\d.]+))/)
const isEdge = ua.match(/Edge\/([\d.]+)/)
// firefox || chrome
if (typeof MouseEvent === 'function' && !isIE && !isEdge) {
var evt = new MouseEvent('click', {
view: window,
bubbles: true,
cancelable: false
})
a.dispatchEvent(evt)
} else {
if (window.navigator.msSaveOrOpenBlob) {
var bstr = atob(url.split(',')[1])
var n = bstr.length
var u8arr = new Uint8Array(n)
while (n--) {
u8arr[n] = bstr.charCodeAt(n)
}
var blob = new Blob([u8arr])
window.navigator.msSaveOrOpenBlob(blob, fileName)
} else {
var html = '' +
'<body style="margin:0;">' +
'<img src="' + url + '" style="max-width:100%;" title="' + fileName + '" />' +
'</body>'
var tab = window.open()
tab.document.write(html)
}
}
}

以上,如有错误,欢迎指正

参考资料

坚持原创技术分享,您的支持将鼓励我继续创作!