需求:用户要求上传.sql文件并解析
实现结果:可上传多个文件,点击可在下方查看,可删除
所用知识点:
FileReader读取文件
FileReader官方可用四种方法读取文件。分别为readAsArrayBuffer(此方法用来将文件存储为二进制数据)、readAsBinaryString(此方法将文件存储为二进制,已废除用readAsArrayBuffer来代替)、readAsDataURL(此方法将文件存储为base64编码格式,常用来读取图片)、readAsText(此方法将文件存储为普通字符串格式)
一下为实现该功能代码:
<template><div><div class="d-flex justify-content-end mb-2"><el-tagclass="mr-1"v-for="(tag, index) in uploadList":key="tag + index + Date"closable@click="handelShowShell(tag)"@close="handelDeleteShell(tag.name, index)"type="success">{{tag.name}}</el-tag><el-uploadclass="upload-demo col-2 text-right"action=""multipleaccept=".sh, .sql":before-upload="handleBeforeUpload"><el-buttontype="text"size="mini"icon="el-icon-upload2">上传脚本</el-button></el-upload></div><div><code-mirror ref="import-code" v-model="commandData.data" class="border"mode="shell" codePlaceholder="###请输入脚本###"></code-mirror></div></div>
</template>
<script>import CodeMirror from "../../../common/CodeMirror";import {showToast, confirm} from "../../../utils/messageUtils";export default {components: {CodeMirror},data() {return {commandData: {},uploadList: []};},methods: {handleBeforeUpload(file) {const fileExt = file.name.split('.').pop().toLocaleLowerCase();if (fileExt === 'sh' || fileExt === 'sql') {this.file = file;this.readData(file);} else {showToast(this, {message: '请选择后缀为"sh"或"sql"的文件', type: 'error'});}return false;},readData(file) {let fileName = file.name;let check = this.uploadList.some(item => item.name === fileName);if (check) {showToast(this, '不能上传重复的文件', 'warning');return;}const reader = new FileReader();reader.readAsText(file);reader.onerror = e => {showToast(this, {message: '读取文件错误', type: 'error'});};reader.onload = e => {this.uploadList.push({name: fileName,data: e.target.result});};},// 点击标签查看shell文件handelShowShell(item) {this.commandData = item;},// 删除shellhandelDeleteShell(tagName, index) {confirm(this, '确认要移除该文件么?').then(res => {if (res === 'confirm') {this.uploadList.splice(index, 1);if (tagName === this.commandData.name) {this.commandData = {data: ''};}}});}}};
</script>
<style lang="scss" scoped></style>