- 将下面代码另存为html文件
- 用浏览器打开
- 点击下载
代码如下: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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<meta charset="utf-8" />
</head>
<body>
<div>输入base64字符串</div>
<textarea id="base64text" rows="10" cols="40"></textarea>
<div>输入文件名</div>
<input id="filename" /><br />
<button id="btnGenerate">下载</button><br />
<a id="btnDownload"></a>
<script>
var base64text = document.getElementById("base64text");
var filename = document.getElementById("filename")
var btnGenerate = document.getElementById("btnGenerate");
var btnDownload = document.getElementById("btnDownload");
var MIME = {
"application/x-zip-compressed": "zip",
"application/javascript": "js",
"text/css": "css",
"text/plain": "txt",
"text/html": "html",
"text/xml": "xml",
"image/jpeg": "jpeg",
"image/png": "png",
"image/gif": "gif",
"image/svg+xml": "svg"
};
//文件名默认当前时间戳
filename.value = Date.now();
//检测点击下载按钮
btnGenerate.addEventListener("click", function (e) {
var fname = filename.value + "." + MIME[getContentType(base64text.value)];
var blob = getBlob(base64text.value);
if (navigator.msSaveBlob) {
navigator.msSaveBlob(blob, fname);
}
else {
btnDownload.download = fname;
btnDownload.href = URL.createObjectURL(blob);
btnDownload.click();
}
});
/**
* 获取Blob
* @param {stirng} base64
*/
function getBlob(base64) {
return b64toBlob(getData(base64), getContentType(base64));
}
/**
* 获取文件类型
* @param {string} base64
*/
function getContentType(base64) {
return /data:([^;]*);/i.exec(base64)[1];
}
/**
* 获取base64中的数据
* @param {string} base64
*/
function getData(base64) {
return base64.substr(base64.indexOf("base64,") + 7, base64.length);
}
/**
* base64转Blob
* @param {string} b64Data
* @param {string} contentType
* @param {number} sliceSize
*/
function b64toBlob(b64Data, contentType, sliceSize) {
contentType = contentType || '';
sliceSize = sliceSize || 512;
var byteCharacters = atob(b64Data);
var byteArrays = [];
for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
var slice = byteCharacters.slice(offset, offset + sliceSize);
var byteNumbers = new Array(slice.length);
for (var i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
var blob = new Blob(byteArrays, { type: contentType });
return blob;
}
</script>
</body>
</html>
演示地址:base64ToFile