elementui图片上传转为base64字符串

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

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代码

    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);
        };
      });
    },

你可能感兴趣的:(element-ui,elementui,前端,javascript)