(Vue+SpringBoot)使用ElementUi的el-upload上传更新用户头像

实现功能如下:

 

点击修改按钮后选择本地文件

 点击打开后修改成功,头像修改完毕。

 -------------------------------------------------

把图片存到数据库

Vue代码:

<el-upload class="avatar-uploader" action="http://localhost:8080/users/updateHeadPortrait"
            :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"
            :data={userId:this.id}>
   <el-button type="primary" style="margin-left: 20px">修改头像</el-button>
</el-upload>



      handleAvatarSuccess(res, file) {
        this.$message({
          showClose: true,
          message: '修改成功',
          type:"success"
        });
        setTimeout(() => {
          location.reload()
        }, 2000);
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      }

点击button后直接发送POST请求,除发送头像外,附加data属性中的信息,这里传值为修改头像的用户的ID。

SpringBoot代码:

    @PostMapping("updateHeadPortrait")
    public String updateHeadPortrait(@RequestParam(value = "userId") String userId , @RequestParam(value = "file")MultipartFile multipartFile){
        try {
            int i = usersRepository.updateHeadProtrait(multipartFile.getBytes(),userId);
            return "success";
        } catch (IOException e) {
            e.printStackTrace();
            return "error";
        }

    }

接受到图片后用getButes()转换为byte[],根据用户ID录入到数据库,图片录入到数据库后,字段类型为Blob,SpringBoot中的实体类与其相对应的字段的类型为byte[]。

至此已经把图片存储到数据库。

-----------------------------------------------------------

从数据库拿到头像显示在界面上

传入数据库的图片可以把它当做是一个巨长无比的字符串,直接用常规方法把它取出来传到前端就可以。

 <el-avatar :src="'data:image/png;base64,'+imageBase64" :size="80"></el-avatar>

这里取出的数据放在了imageBase64中,前面加上'data:image/png;base64,'即可显示出图片。

--------------------------------------------

还有另一种方式可以实现:Vue 读取后台二进制文件流转为图片显示 - 饕 - 博客园

这种转路径的方式我没成功,大家可以试一下,这个好像更好些。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值