Vue2下载base64格式的Excel文件
Xplorist Lv6

Vue2下载base64格式的Excel文件

HTML

  • index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>test</title>
</head>
<body>
<div id="app">
<button v-on:click="exportBusLineStation()">导出公交站点Excel</button>
</div>
</body>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue@2.7.14/dist/vue.js"></script>
<script type="text/javascript" src="./js/index.js"></script>
</html>

JavaScript

  • ./js/index.js
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
let app = new Vue({
el: '#app',
data: {

},
created: function () {

},
methods: {
dataURLtoBlob: function (dataurl) {
try {
let arr = dataurl.split(',');
let mime = arr[0].match(/:(.*?);/)[1];
let bstr = atob(arr[1]);
let n = bstr.length;
let u8arr = new Uint8Array(n);

while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], { type: mime });
} catch {
let arr = dataurl.split(',');
let bstr = atob(arr[0]);
let n = bstr.length;
let u8arr = new Uint8Array(n);

while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr]);
}
},
exportBusLineStation: function () {
axios({
method: 'post',
url: '/api/device/baseData/exportBusLineStation',
data: {}
}).then(response => {
let contentDisposition = response.headers['content-disposition'];
let fileName = contentDisposition.substring(contentDisposition.indexOf('=') + 1);
let data = this.dataURLtoBlob(response.data.data);
let url = window.URL.createObjectURL(new Blob([data]));
let link = document.createElement('a');
link.href = url; // <a>下载文件
//this.imgSrc = url; // <img>显示图片
link.setAttribute('download', decodeURIComponent(fileName));
document.body.appendChild(link);
link.click();
}).catch(error => {
alert("文件下载失败");
console.log(error);
});
},
},
});
 评论