在 Vue 中读取本地文本文件(兼容各种浏览器)
<template>
<div class="box">
<input type="file" ref="inputFile" @change="handleExportFile" style="display: none" />
<button type="button" @click="handleExportFile('click')">点击加载文件内容</button>
</div>
</template>
<script>
export default {
methods: {
handleExportFile(mark) {
if (mark === "click") {
this.$refs.inputFile.click();
} else {
this.uploadFile(this.$refs.inputFile, (content) => {
console.log(JSON.parse(content)); //打印读取的文件内容
});
}
},
uploadFile(input, callBack){
//支持chrome IE10
if (window.FileReader) {
let file = input.files[0], filename = file.name.split(".")[0];
let reader = new FileReader();
reader.onload = function () {
// console.log(this.result);
callBack(this.result, filename)
}
reader.readAsText(file);
}
//支持IE 7 8 9 10
else if (typeof window.ActiveXObject != 'undefined') {
let xmlDoc;
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.load(input.value);
callBack(xmlDoc.xml)
}
//支持FF
else if (document.implementation && document.implementation.createDocument) {
let xmlDoc;
xmlDoc = document.implementation.createDocument("", "", null);
xmlDoc.async = false;
xmlDoc.load(input.value);
callBack(xmlDoc.xml)
} else {
console.error('文件读取失败!')
}
}
}
};
</script>
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
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
上次更新: 2024/01/30, 00:35:17
- 02
- Node与GLIBC_2.27不兼容解决方案08-19
- 03
- Git清空本地文件跟踪缓存08-13