WEBAPI之FilerReader上传图片预览图片预览

260 阅读1分钟

有时候经常会遇到上传图片需要进行回显,但是又不能直接选择图片上传到服务器,在网上也没有找到相应的教程,于是自己摸索出来一个方法

这里用的是element-ui的上传

其实用什么都一样,只不过是样子懒得写。。。。

<el-upload ref="upload" 
    class="avatar-uploader" 
    action="http://localhost:8000/blog/pub" 
    :show-file-list="false" 
    :on-success="handleAvatarSuccess" 
    :on-change="onChange" //监听文件改变 
    :auto-upload="false" //取消element-ui的自动上传 > 
    <img v-if="imgFile" :src="imgFile" class="avatar" /> //上传的图片预览 
    <img v-else-if="blog.pic" :src="blog.pic" class="avatar" /> //原有的图片展示 
    <i v-else class="el-icon-plus avatar-uploader-icon"></i> //未上传图片 
</el-upload>  

文件改变之后

 onChange(file) {
      console.log(file.raw);  //这里eleui 会把文件存在file.raw下,可能是我当时有附带参数的原因,大家可以自行测试
      const isJPG = file.raw.type === "image/jpeg";
      const isPNG = file.raw.type === "image/png";
      const isLt2M = file.raw.size / 1024 / 1024 < 5;
      if (!isPNG && !isJPG) {
        this.$message.error("上传头像图片只能是 JPG/PNG 格式!");
        var image = true;
        clearFiles();
      }
      let that = this;
            //创建读取文件的对象
      var reader = new FileReader();
      //创建文件读取相关的变量   只有文件读取的时候才会触发这个函数
      reader.onload = function (e) {
        // console.log(that.imgFile);
        // console.log(that);
        that.imgFile = e.target.result;  //文件进行读取然后进行src绑定
      };
      //正式读取文件  只有读取了文件才会触发 reader.onload 函数
      reader.readAsDataURL(file.raw);
      this.fileData.append("file", file.raw);
    }