前端主导文件处理方法
# 1.应用场景
# application:应用于前后端接口联调上传下载文件,可拓展优化为大量数据切片上传,或断点下载。
//下载方法 需要配合把axios二次封装的responseType写为blob!!
exportFile(content, customFileName, type) {
let filename = content.filename || customFileName;
let URL = window.URL || window.webkitURL;
let objectUrl = URL.createObjectURL(content);
let a = document.createElement("a");
a.href = objectUrl;
a.download = filename; //这步要注意 filename要写成 '文件名.xlsx'
document.body.appendChild(a);
a.click();
a.remove();
}
直接调用接口返回的数据流就可以使用了,例如返回的数据流为res,第二个参数可以自定义下载文件的名字
this.exportFile(res, '导出模板.xlsx')
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
//导入方法 直接用 Vue2的模板展示
uploadfile(){
console.log('导入');
const _this = this;
// const fileType = [
// "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
// "application/vnd.ms-excel"
// ];
const fileType = ['xlsx']
const inputFile = document.createElement("input")
inputFile.type = "file"
inputFile.style.display = "none"
document.body.appendChild(inputFile)
inputFile.click()
inputFile.addEventListener("change",async function() {
const file = inputFile.files[0];
var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
if (!fileType.includes(testmsg)) {
_this.$message.warning("上传的文件格式只能是xlsx");
document.body.removeChild(inputFile);
return false;
}
const formData = new FormData();
formData.append("file", file);
const res = await importTaskRuleStore(_this.$route.query.id,formData)
console.log(res);
_this.$modal.msgSuccess("操作成功");
_this.initTableList(_this.$route.query.taskRuleNumber,{pageNum:_this.pageNum,pageSize:_this.pageSize})
})
}
//可以直接调用上传,只需要改一下对应的接口地址就可以了。非常好用。有的时候el-upload会有一些样式方面的缺陷,这个时候用这个自定义的方法就挺好。 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
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
上次更新: 2023/07/06, 09:51:30