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

文章讲述了在Vue.js项目中,使用el-upload组件上传图片并转换为base64字符串的过程。开发者最初尝试了上传图片到服务器,但发现后端需要的是base64格式。因此,调整了方法,通过FileReaderAPI读取上传的图片文件并将其转换为base64,实现了无需服务器存储即可提供给后端所需数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实现一个小功能,上传一张签名图片,转为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

### 显示 Base64 编码的图片 为了在 Element Plus 中显示 Base64 编码的图片,通常的做法是在前端将文件读取并换为 Base64 字符串,然后将其设置给 `<img>` 标签的 `src` 属性。 #### 使用 FileReader API 图片Base64 并展示 当用户通过文件输入框选择了一张图片之后,可以通过 JavaScript 的 `FileReader` 对象来读取这个文件的内容,并把它化为 Base64 编码形式。一旦化完成,就可以把这个字符串赋值给图像元素的源属性从而实现在网页上查看所选图片的效果[^2]。 下面是一个简单的 Vue 组件例子展示了这一过程: ```html <template> <div> <!-- 文件上传控件 --> <el-upload class="upload-demo" action="" :auto-upload="false" :on-change="handleChange"> <el-button type="primary">点击上传</el-button> </el-upload> <!-- 图片预览区域 --> <div v-if="imageUrl" style="margin-top: 20px;"> <h3>预览:</h3> <img :src="imageUrl" alt="" width="200"/> </div> </div> </template> <script> export default { data() { return { imageUrl: '' }; }, methods: { handleChange(file) { let reader = new FileReader(); reader.readAsDataURL(file.raw); reader.onloadend = () => { this.imageUrl = reader.result; } } } } </script> ``` 在这个实例中,每当选择了新的文件时就会触发 `handleChange()` 方法,在此方法内部创建了一个新的 `FileReader` 实例用于异步读取文件内容;当读取操作结束(`loadend`)的时候会执行指定的回调函数,此时可以访问到已经好的 Base64 数据流,并将其存储起来以便后续作为 img 标签 src 值使用[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值