Element 上传JSON文件,解析内容
- 使用 element 上传组件,FileReader 解析 JSON 文件。
template 代码
<el-dialog title="提示" :visible.sync="dialogVisible" width="25%">
<el-row class="dialogBox">
<el-upload
drag
action
accept=".json"
:auto-upload="false"
:on-change="updateReason"
>
<i class="el-icon-upload"></i>
<div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
<div class="el-upload__tip" slot="tip">
* 只能上传1个JSON文件
</div>
</el-upload>
</el-row>
<span slot="footer" class="dialog-footer">
<el-button @click="handleCacel">取 消</el-button>
<el-button type="primary" @click="handleOK">确 定</el-button>
</span>
</el-dialog>
JS方法代码
// 每次最多只能上传一个,多余的删除,保留最新的,上传文件变化触发
updateReason(file, fileList) {
if (fileList.length === 2) {
fileList.shift();
}
this.fileList = fileList;
},
// 确定方法,解析JSON文件
handleOK() {
let reader = new FileReader(); //新建一个FileReader
reader.readAsText(this.fileList[0].raw, "UTF-8"); //读取文件
reader.onload = (evt) => {
//读取文件完毕执行此函数
const dataJson = JSON.parse(evt.target.result);
// dataJson 就是读取的文件内容
this.dialogVisible = false;
};
},
readAsText 方法可以将 Blob 或者 File 对象转根据特殊的编码格式转化为内容 (字符串形式)
这个方法是异步的,也就是说,只有当执行完成后才能够查看到结果,如果直接查看是无结果的,并返回 undefined

浙公网安备 33010602011771号