我无法读取JSON文件的内容,我尝试通过ReadFile访问文件的内容,但未成功,但内容的字符串为空并且url未定义,
我的代码:
<template>
<div class="large-12 medium-12 small-12 cell">
<input type="file" accept="application/JSON" @change="onFileChange" class="inputFile" />
</div>
</template>
<script>
import Vue from "vue";
export default {
data() {
return {};
},
methods: {
onFileChange(e) {
let files = e.target.files || e.dataTransfer.files;
if (!files.length) return;
this.readFile(files[0]);
},
readFile(file) {
let reader = new FileReader();
reader.onload = e => {
this.readContentFile = e.target.result;
console.log(this.readFile);
};
let url = reader.readAsDataURL(file);
let content =reader.result;
console.log(url);
console.log(content);
}
}
};
</script>
你差点就吃了。reader.onload就像文件完成加载时的回调一样,因此靠近底部的console.logs会在文件加载之前发生。希望您会发现此片段对您有所帮助。
new Vue ({
el: "#app",
methods: {
onFileChange(e) {
let files = e.target.files || e.dataTransfer.files;
if (!files.length) return;
this.readFile(files[0]);
},
readFile(file) {
let reader = new FileReader();
reader.onload = e => {
console.log(e.target.result);
let json = JSON.parse(e.target.result);
};
reader.readAsText(file);
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div class="large-12 medium-12 small-12 cell" id="app">
<input type="file" accept="application/json" @change="onFileChange">
</div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句