element-plus el-upload 上传图片转base64 字符串

实现一个小功能,上传一张签名图片,转为base64 字符串格式,从来没做过上传图片的功能,只能仿照别人的页面来做,压根也没搞清楚逻辑就复制粘贴,当然是上传不上去的啦,因为后端要的是base64 格式,而我复制的那个页面是上传图片到服务器的!!!

首先把人家写的上传图片/文件到服务器记下来(这里上传调用了接口的):

<el-form-item label="封面图片:">
    <el-upload class="avatar-uploader" :show-file-list="false" :before-upload="beforeAvatarUpload" :http-request="uploadImageFile">
        <img v-if="addForm.imgPathShow" :src="addForm.imgPathShow" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon">
            <Plus />
        </el-icon>
    </el-upload>
</el-form-item>
<el-form-item label="上传文件:" width="100%">
    <el-upload class="upload-demo" action="" :on-remove="handleRemove" :before-remove="beforeRemove" multiple :limit="3" :on-exceed="handleExceed" :http-request="UploadFile" :on-change="onChangeFile">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip"></div>
     </el-upload>
</el-form-item>
     import * as Plus from "@element-plus/icons-vue";
     export default {
          components: { Plus },
          data() {
              addForm: {
                imgPathShow: "",
              },
              fileIds: [],
              upFileList: [],
              fileList: [],
              fileCodeList: [],
          }
      }

    /**
     * 上传封面图片前检查
     */
    beforeAvatarUpload(rawFile) {
      if (rawFile.type !== "image/jpeg") {
        this.$msgbox.alert("请上传JPEG格式的图片文件!");
        return false;
      } else if (rawFile.size / 1024 / 1024 > 2) {
        this.$msgbox.alert("封面图片的大小请小于2MB!");
        return false;
      }
      return true;
    },
    /**
     * 上传封面图片到服务器
     */
    uploadImageFile(options) {
      let file = options.file;
      let uploadForm = new FormData();
      uploadForm.append("FileCategoryCode", "Train");
      uploadForm.append("FileCategoryName", "培训");
      uploadForm.append("Desc", "封面");
      uploadForm.append("file", file);
      //删除文件
      this.DeleteFileData(file);
      if (this.fileImgCode != "") {
        this.deleteFiles.push(this.fileImgCode);
      }
      Req.UploadFiles(uploadForm).then((res) => {
        if (res.data) {
          if (res.data.isSuccess) {
            this.fileIds.push({
              uid: options.file.uid,
              fileCode: res.data.fileCodeList[0],
            });
            this.addForm.imgPathShow =
              process.env.VUE_APP_BASE_IMAGE_URL + res.data.filePathList[0];
            this.addForm.imgPath = res.data.filePathList[0];
            // 使图片显示
            this.addForm.imgPathShow = URL.createObjectURL(file);
          }
        }
      });
    },

    handleExceed(files, fileList) {
          this.$message.warning(`当前限制选择 3 个文件,本次选择了 ${files.length} 个文件,共        
                选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}?`);
    },
    handleRemove(file, fileList) {
      //如果是添加则真删,如果是修改,则记录到缓存中
      if (file.fileCode) {
        this.deleteFiles.push(file.fileCode);
      } else {
        this.DeleteFileData(file);
      }
    },

     /**
     * 删除文件
     * @param {文件对象} file
     */
    DeleteFileData(file) {
      let obj = this.fileIds.filter((f) => f.uid == file.uid)?.[0];
      if (obj) {
        Req.DeleteFile({ code: obj.fileCode }).then((res) => {
          if (res.data) {
            let index = this.fileIds.findIndex((f) => f.uid == file.uid);
            this.fileIds.splice(index, 1);
            console.log(this.fileIds);
          }
        });
      }
    },
    onChangeFile(file) {
      const isLt1024M = file.size / 1024 / 1024 < 1024;
      if (!isLt1024M) {
        this.$msgbox.alert("上传文件大小不能超过 1024MB!");
        return false;
      }
      return true;
    },

    /**
     * 上传文件
     */
    UploadFile(options) {
      let uploadForm = new FormData();
      uploadForm.append("FileCategoryCode", "Train");
      uploadForm.append("FileCategoryName", "培训");
      uploadForm.append("file", options.file);
      Req.UploadFiles(uploadForm).then((res) => {
        if (res.data) {
          if (res.data.isSuccess) {
            this.fileIds.push({
              uid: options.file.uid,
              fileCode: res.data.fileCodeList[0],
            });
          }
        }
      });
    },

接下来,实现上传图片转为base64格式

这里用到的组件是el-upload,这里上传图片会被转为file格式,我一开始没有注意,一直按照上面上传图片到服务器想的是,我们能拿到图片路径,那么就去转路径为base64,后来在大佬的帮助下,才知道后端需要的只是base64格式的字符串,不需要图片,所以我不需要上传图片到服务器,而且我用的组件会把图片转为file,所以我只要知道如何把file转为base64就可以了!

<el-form-item label="签名图片:">
        <el-upload class="avatar-uploader" :show-file-list="false" :before-upload="beforeAvatarUpload"
          :http-request="uploadImageFile">
          <img v-if="addForm.imgPathShow" :src="addForm.imgPathShow" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
export default {
  components: { Plus },
  data() {
    return {
      imageBase64:'',
    };
  },

  methods: {
    /**
    * 上传封面图片
    */
    uploadImageFile(options) {
      let that = this;
      let file = options.file;
      this.addForm.imgPathShow = URL.createObjectURL(file);
      var reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onloadend = function(){
        // 将文件(file)转换成base64字符串
        that.imageBase64 = reader.result;
      }
     },

    /**
     * 上传封面图片前检查
     */
    beforeAvatarUpload(rawFile) {
      if (rawFile.type !== "image/jpeg") {
        this.$msgbox.alert("请上传JPEG格式的图片文件!");
        return false;
      } else if (rawFile.size / 1024 / 1024 > 2) {
        this.$msgbox.alert("封面图片的大小请小于2MB!");
        return false;
      }
      return true;
    },

   

  },
};

注意:base64 在保存之后,关闭dialog弹窗时需要清空,否则下次上传的还是之前的base64格式

本文  // 将文件(file)转换成base64字符串  采用了https://www.5axxw.com/questions/simple/5mfcku

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值