前端上传文件保存到变量中

需求:

用户点击上传按钮,将用户从本地上传的文件展示到页面上进行预览,没有和后端交互纯前端。

 


实现思路:

1.使用input标签做上传

 <input ref="inputRef" id="data2" @click="uploadJson" type="file" />

2.监听input的change事件

input.onchange = function (e) {console.log(e)} //上传的数据在e对象里面

3.使用 FileReader()将文件解析并保存到变量,下面是具体代码,核心代码就两句

var reader = new FileReader()
reader.readAsText(file, "utf-8")//如果乱码还可以用gbk编码

实现代码:

uploadJson () {
      let that = this  //先拿一下this指向vue
      //页面的input属性id值,这里写自己的
      var input = document.getElementById("data2")
      input.onchange = function (da) {
        var file = da.path[0].files[0] //这个地方先打印下da,看看数据在哪里
        console.log('3333', file)
        if (true) {
          var reader = new FileReader()
          reader.readAsText(file, "utf-8")//还可以用gbk编码,我是utf8
          reader.onload = function (da) {
            that.daoRuJson = JSON.parse(da.target.result) 
            that.openOrCloEditor = true//将数据保存到自己设置的变量
          }
        }
      }
    },

猜你喜欢

转载自blog.csdn.net/wanghaoyingand/article/details/125449101