<div>
<div class="file-block">
<div class="upload-block" v-if="!uploadSuccess">
<el-upload v-model="ruleForm.customRules"
:action="action"
:limit="1"
:before-upload="beforeUpload"
:on-success="uploadSuccess"
:file-list="fileList">
<el-button class="upload">点击上传</el-button>
</el-upload>
</div>
<div class="file" v-if="uploadSuccess">
<span class="file-name">{{jsonfileName}}</span>
<el-button type="text" @click="delJSON">删除</el-button>
</div>
<el-button type="text" @click="download">下载模板</el-button>
</div>
<div class="el-upload__tip">上传大小限制64kb,文件内容为JSON格式</div>
</div>
<script>
export default {
data () {
return {
ruleForm:{
customRules:'',//需提交的值
},
action:'……',//上传文件的地址
fileList:'',
uploadSuccess:false,
jsonfileName:''//文件名
}
},
methods:{
//上传限制
beforeUpload(file){
const fileName = file.name;
const fileType = fileName.substring(fileName.lastIndexOf("."));
if (fileType==='.json'||fileType==='.JSON') {
}else{
this.$message.error('暂不支持该文件格式');
return false
}
if (file.size/1024>64) {
this.$message.error("文件不能大于64kb")
return false
}
},
//上传成功读取文件
uploadSuccess(res,file){
this.jsonfileName=file.name
this.uploadSuccess=true
let val=''
let reader=new FileReader();
reader.readAsText(file.raw,'UTF-8')//读取,转换字符编码
let vm=this
reader.onload=function(e){
val=e.target.result;//获取数据
if(vm.checkJSON(val)){
vm.uploadSuccess=true
vm.ruleForm.customRules=val
}else{
vm.uploadSuccess=false
vm.ruleForm.customRules=''
vm.$message.error("JSON格式不符合规范");
}
}
if (this.ruleForm.customRules) {
this.$nextTick(()=>{
this.$refs.ruleForm.clearValidate(["customRules"]);
})
}
},
//try……cache与JSON.parse()校验JSON格式
checkJSON(val){
if(val){
try {
JSON.parse(val);
return true;
} catch(e) {
return false;
}
}
},
//删除文件
delJSON(){
this.uploadSuccess=false
this.ruleForm.customRules=''
},
//下载模板
download(){
let obj = {
value1: 'value1',
value2: 'value2'
}
let model=JSON.stringify(obj)
const blob = new Blob([model], { type: "application/json;charset=utf-8" });
const href = URL.createObjectURL(blob);
const alink = document.createElement("a");
alink.style.display = "none";
alink.download = "模板.json";
alink.href = href;
document.body.appendChild(alink);
alink.click();
document.body.removeChild(alink);
URL.revokeObjectURL(href);
}
}
}