修改前

通过提交表单获取文件

1
2
3
4
5
6
7
8
9
document.body.appendChild(form)
form.method = 'POST'
form.action = baseURL + 'export/toClAccessRecordDetailExport?carLicense=' + vm.carLicense +
"&beginTime=" + sTime +
"&endTime=" + eTime + "&assessType=" + vm.select.assessType + "&carType=" + vm.select
.carType + "&unitId=" + exportUnitId + "&materialName=" + vm.select.materialName +
"&bayonetId=" + vm.select.bayonetId + "&applyType=" + vm.select.applyType + "&contact=" + vm.select.contact
+ "&contactNumber=" + vm.select.contactNumber + "&idCard=" + vm.select.idCard;
form.submit()

修改原因

form提交无法自定义header导致无法校验传输token,接口无权限会被整改

image-20220802151010866

修改后

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
const url = baseURL + 'export/toClAccessRecordExport?carLicense=' + vm.carLicense +
"&beginTime=" + sTime +
"&endTime=" + eTime + "&assessType=" + vm.select.assessType + "&carType=" + vm.select
.carType + "&unitId=" + exportUnitId + "&bayonetId=" + vm.select.bayonetId + "&contact=" + vm.select.contact
+ "&contactNumber=" + vm.select.contactNumber + "&idCard=" + vm.select.idCard + "&applyType=" + vm.select.applyType;
const xhr = new XMLHttpRequest();
// 根据接口设定提交方式
xhr.open('POST', url, true);
// 设置token
xhr.setRequestHeader('token', 'xxxxxxxx');
xhr.setRequestHeader('Content-Type', 'application/octet-stream');
// 返回类型blob
xhr.responseType = 'blob';
xhr.onload = function(e) {
if (this.status === 200) {
const blob = this.response;
const reader = new FileReader();
reader.readAsDataURL(blob); // 转换为base64,可以直接放入a表情href
reader.onload = function(e) {
const a = document.createElement('a');
// 以当前时间作为文件名称
a.download = parseTime(new Date(), '{y}{m}{d}{h}{i}{s}') + '.xls';
a.href = e.target.result;
document.documentElement.appendChild(a);
a.click();
// 等价于document.documentElement.removeChild(a);
a.remove();
};
}
};
// 发送ajax请求
xhr.send();

时间格式化的方法

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
function parseTime(time, pattern) {
if (arguments.length === 0 || !time) {
return null
}
const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
let date
if (typeof time === 'object') {
date = time
} else {
if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
time = parseInt(time)
} else if (typeof time === 'string') {
time = time.replace(new RegExp(/-/gm), '/')
}
if ((typeof time === 'number') && (time.toString().length === 10)) {
time = time * 1000
}
date = new Date(time)
}
const formatObj = {
y: date.getFullYear(),
m: date.getMonth() + 1,
d: date.getDate(),
h: date.getHours(),
i: date.getMinutes(),
s: date.getSeconds(),
a: date.getDay()
}
const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
let value = formatObj[key]
// Note: getDay() returns 0 on Sunday
if (key === 'a') {
return ['日', '一', '二', '三', '四', '五', '六'][value]
}
if (result.length > 0 && value < 10) {
value = '0' + value
}
return value || 0
})
return time_str
}

效果展示