Element ui 使用upload 读取本地文件并填充到输入框内

目录

一、问题背景

二、解决方案 

具体思路

 代码示例

示例效果


一、问题背景


       最近在写vue项目的时候需要一个组件来读取本地中的json文件并将内容填充到输入框中。并且最后需要对json格式做校验。

二、解决方案 


        由于浏览器不能使用js直接读取文件,因此考虑使用element ui 中的upload组件获取文件信息,然后使用js 中的fileReader读取文件内容。

具体思路


1)使用upload组件读取文件信息。
2)使用js中的fileReader 读取文件。

3)对读取出的内容做格式校验。
 

代码示例

<template>
          <el-row>
            <div class="uploadDemo">
              <el-col span= 8>	
                  <span slot="label">
                    <span class="span-box">
                    <i class="el-icon-info" ></i>
                    <span>demo </span>
                    </span>
                  </span>
                  <el-input v-model="demo" type="textarea" :autosize="{ minRows: 3,maxRows: 10}" placeholder="请输入json格式"></el-input>
              </el-col>
              <el-col span= 4>
                <el-upload
                  class="upload-demo"
                  ref="upload"
                  accept=".json"
                  action=''
                  :on-change="changeDemoFile"
                  :file-list="demoFileList"
                  :auto-upload="false">
                  <el-button slot="trigger" size="small" type="primary">选取文件填充</el-button>
                  <div slot="tip" class="el-upload__tip">只能读取json文件</div>
                </el-upload>
              </el-col>
            </div>
          </el-row>
        </el-form>
 
</template>
 
<script>
export default {
  data () {
    return {
      // data for upload files
      demo: null,
      demoFileList: [],
    }
  },
  methods: {
    changeDemoFile(file,demoFileList){
      if (demoFileList.length == 2) {	//只保留最新的文件
        demoFileList.shift()
      }
      if(file.name.slice(-5) != '.json'){
        alert("只能读取json文件,请重新选择")
        demoFileList= []
      }else{
        // console.log(file.raw);
        let fileReader= new FileReader()
        fileReader.onload = async (e) => {
            try {
              let document = JSON.parse(e.target.result)
              console.log(document)
              this.demo = JSON.stringify(document)
              if(this.isJSON(this.demo)){
                this.$message('满足json格式')
              }else {
                this.$message('不满足json格式,请重新选择文件或修改文件。')
              }
            } catch (err) {
              console.log(`load JSON document from file error: ${err.message}`)
              demoFileList = []
              this.showSnackbar(`Load JSON document from file error: ${err.message}`, 4000)
              alert('填充失败,请重新选择文件或手动输入。')
            }
        }
        fileReader.readAsText(file.raw)
      }
    },
    isJSON(str) {
      // 判断一个string是否是json类型,用于格式校验
        if (typeof str == 'string') {
            try {
                var obj=JSON.parse(str);
                if(typeof obj == 'object' && obj ){
                    return true;
                }else{
                    return false;
                }
    
            } catch(e) {
                console.log('error:'+str+'!!!'+e);
                return false;
            }
        }
        console.log('It is not a string!')
    }
  }
}
</script>

示例效果
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值