elementui图片上传转为base64字符串

场景:后端需要将上传的图片文件作为base64字符串的方式传参给他。

html代码

html 复制代码
      <div class="upload_box">
                  <el-upload
                    class="upload-demo"
                    ref="upload"
                    action="#"
                    :show-file-list="false"
                    :http-request="
                      (file) => {
                        return httpRequest(file, item);
                      }
                    "
                   
                    style="display: inline-block"
                  >
                    <img
                      v-if="item.darkBg"
                      :src="'data:image/jpg;base64,' + item.darkBg"
                      class="avatar"
                    />
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  </el-upload>
                </div>

js代码

javascript 复制代码
    httpRequest(data, item) {
      
      // 转base64

      this.getBase64(data.file).then((resBase64) => {
        item.darkBg = resBase64.split(",")[1];
      });
    },

    // 转base64编码
    getBase64(file) {
      this.dialogVisible = false;
      return new Promise((resolve, reject) => {
        let reader = new FileReader();
        let fileResult = "";
        reader.readAsDataURL(file); //开始转
        reader.onload = function () {
          fileResult = reader.result;
        };
        //转失败
        reader.onerror = function (error) {
          reject(error);
        };
        //转结束 resolve 出去
        reader.onloadend = function () {
          resolve(fileResult);
        };
      });
    },
相关推荐
mCell1 天前
GSAP ScrollTrigger 详解
前端·javascript·动效
gnip1 天前
Node.js 子进程:child_process
前端·javascript
excel1 天前
为什么在 Three.js 中平面能产生“起伏效果”?
前端
excel1 天前
Node.js 断言与测试框架示例对比
前端
天蓝色的鱼鱼1 天前
前端开发者的组件设计之痛:为什么我的组件总是难以维护?
前端·react.js
codingandsleeping1 天前
使用orval自动拉取swagger文档并生成ts接口
前端·javascript
石金龙1 天前
[译] Composition in CSS
前端·css
白水清风1 天前
微前端学习记录(qiankun、wujie、micro-app)
前端·javascript·前端工程化
Ticnix1 天前
函数封装实现Echarts多表渲染/叠加渲染
前端·echarts
用户22152044278001 天前
new、原型和原型链浅析
前端·javascript