Vue+element ui+springboot实现用户头像修改

头像上传

前台上传文件可以直接用element ui的上传组件

		<el-upload
            class="avatar-uploader"
            action="http://localhost:8080/Login/upload"//上传的地址,即是后台保存文件的接口
            :show-file-list="false"//是否显示已上传文件列表
            :on-success="handleAvatarSuccess"//成功之后执行的函数
            :data="{'userId':user.eid,'status':userStatus}"//传入后台的用户状态和用户ID(注意要是对象)
            :before-upload="beforeAvatarUpload"//上传前执行的函数判断图片格式
            style="display: inline-block;width: 300px"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar">//上传成功后展示的图片
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>

          </el-upload>
        handleAvatarSuccess(res, file) {
          this.imageUrl = URL.createObjectURL(file.raw);
          console.log(URL.createObjectURL(file.raw))
          console.log(this.imageUrl)
          console.log(res)
        },
        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;
        },

后台接收

 	/**
     * 修改头像
     */
    @PostMapping("/upload")
    public String singleFileUpload(@RequestParam("file") MultipartFile file,
                                   HttpServletRequest request,Long userId,String status) {
		//@RequestParam("file") MultipartFile file为接收图片参数
		//Long userId,String status 用户Id和状态

        try {
            byte[] bytes = file.getBytes();
            String imageFileName = file.getOriginalFilename();
            String fileName = UpPhotoNameUtils.getPhotoName("img",imageFileName);
            Path path = Paths.get("C:\\框架\\D4\\d4_pc_ui\\src\\assets\\images\\img\\" + fileName);
          //“C:\\框架\\D4\\d4_pc_ui\\src\\assets\\images\\img\\”为本地目录
            Files.write(path, bytes);//写入文件
            String avatar_url=fileName;
            if (status.equals("学生")){//判断学生状态调用dao层方法,把图片名称写入数据库
                studentService.updateAvatar(userId,avatar_url);//dao层方法
            }
            else {
                teacherService.updateAvatar(userId,avatar_url);
            }
            System.out.println(fileName+"\n");
            return fileName;//返回文件名字
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }
    

根据时间生成图片名称,防止图片名称重复

import java.util.Calendar;

public class UpPhotoNameUtils {
    public static String getPhotoName(String name,String imageFileName){
        String fileName = name;
        Calendar cal=Calendar.getInstance();
        //如果年的目录不存在,创建年的目录
        int year=cal.get(Calendar.YEAR);
        fileName=fileName + "_" + year;
        //如果月份不存在,创建月份的目录
        int month=cal.get(Calendar.MONTH)+1;
        fileName=fileName+"_";
        if(month<10)
        {
            fileName=fileName+"0";
        }
        fileName=fileName+month;
        //生成文件名的日部分
        int day=cal.get(Calendar.DAY_OF_MONTH);
        fileName=fileName+"_";
        if(day<10)
        {
            fileName=fileName+"0";
        }
        fileName=fileName+day;
        //生成文件名的小时部分
        int hour=cal.get(Calendar.HOUR_OF_DAY);
        if(hour<10)
        {
            fileName=fileName+"0";
        }
        fileName=fileName+hour;
        //生成文件名的分钟部分
        int minute=cal.get(Calendar.MINUTE);
        if(minute<10)
        {
            fileName=fileName+"0";
        }
        fileName=fileName+minute;
        //生成文件名的秒部分
        int second=cal.get(Calendar.SECOND);
        if(second<10)
        {
            fileName=fileName+"0";
        }
        fileName=fileName+second;
        //生成文件名的毫秒部分
        int millisecond=cal.get(Calendar.MILLISECOND);
        if(millisecond<10)
        {
            fileName=fileName+"0";
        }
        if(millisecond<100)
        {
            fileName=fileName+"0";
        }
        fileName=fileName+millisecond;
        //生成文件的扩展名部分,只截取最后单位
        String endName = imageFileName.substring(imageFileName.lastIndexOf("."));//截取之后的值
        fileName=fileName+ endName;
        return fileName;
    }
}

要是有服务器,可直接存入服务器,后面存入数据库就可以直接是图片在服务器的路径,前台就可以直接使用,更加方便一些
(ps:这个后台接口参考了一篇博文,暂时没找到)

前台读取并展示

由于没有服务器,存进数据库的是图片的名称在这里插入图片描述
所以需要在前台处理一下

 userAvatarUrl:require("../../assets/images/img/"+this.$store.getters.userInfo.avatarUrl),

注意: require非常重要,如果没有它将无法识别路径,userAvatarUrl将只是一个字符串(后面的this.$store.getters.userInfo.avatarUrl是存到vuex里面的用户的头像名称)

小白一个,如有错误请大佬斧正!

  • 10
    点赞
  • 44
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
实现头像上传,可以结合Spring Boot后端框架,Vue前端框架以及Element UI组件库进行实现。 首先,在Vue前端页面中,可以使用Element UI中的Upload组件实现文件上传功能。可以在页面中定义一个Upload组件,设置action属性为上传接口的URL,设置headers属性为请求头部信息,设置on-success属性为上传成功后的回调函数。具体代码如下: ``` <template> <div> <el-upload class="avatar-uploader" action="/api/uploadAvatar" :headers="{ Authorization: 'Bearer ' + token }" :show-file-list="false" :on-success="handleSuccess"> <img v-if="imageUrl" :src="imageUrl" class="avatar"> <i v-else class="el-icon-plus avatar-uploader-icon"></i> </el-upload> </div> </template> <script> import { getToken } from '@/utils/auth' export default { data() { return { imageUrl: '', token: getToken() } }, methods: { handleSuccess(response) { this.imageUrl = response.data.url } } } </script> ``` 其中,token是用于认证的令牌,可以通过getToken函数获取。handleSuccess函数是上传成功后的回调函数,其中response.data.url表示上传成功后的图片URL。 然后,在Spring Boot后端接口中,可以使用Spring MVC的注解@RequestParam来接收上传的文件。具体代码如下: ``` @RestController @RequestMapping("/api") public class UploadController { @PostMapping("/uploadAvatar") public JsonResult uploadAvatar(@RequestParam("file") MultipartFile file) throws IOException { // 处理上传的文件 return JsonResult.ok("url", "http://www.example.com/avatar.jpg"); } } ``` 其中,@PostMapping注解表示接收POST请求,@RequestParam("file")注解表示接收名为file的文件参数。处理上传的文件后,可以返回一个JsonResult对象,其中包含上传成功后的图片URL。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值