当前位置:   article > 正文

Springboot + elementUI实现上传用户头像

Springboot + elementUI实现上传用户头像

最近一直在做一个背单词的小项目练手,准备着加入个新功能,想了很多种办法,本来准备利用sm.ms图床,把用户头像上传到图床然后返回链接把链接存到数据库里,后来想了想,感觉用户的头像存在那不太好,于是还是决定把用户头像存储在项目里的一个文件夹好了。

ElementUI提供了upload的组件 组件 | Element官方文档 对于我这种没啥艺术细胞的人就只能用人家提供的框架拉(不过说实话我觉得element的组件还是都挺好看的捏)我们这里就直接使用这个组件,然后我这里就直接使用自动上传了。

我想实现的功能就是用户头像下面有个按钮,点击会弹出一个窗口,是用来上传用户头像的,所以还需要用到Dialog的组件,下面是我的HTML部分代码

  1.  <el-button plain @click="avatarDialog = true">更换头像</el-button>
  2.  ​
  3.  <el-dialog title="更换头像"
  4.             :visible.sync="avatarDialog"
  5.             width="80%">
  6.   <el-upload class="avatar-uploader"
  7.                 action="/api/up/avatar"
  8.                 :show-file-list="false"
  9.                 :on-success="handleAvatarSuccess"
  10.                 :before-upload="beforeAvatarUpload">
  11.   <img v-if="imageUrl" :src="imageUrl" class="avatar">
  12.     <i v-else class="el-icon-plus avatar-uploader-icon"></i>
  13.      </el-upload>
  14.          <span slot="footer" class="dialog-footer">
  15.   <el-button @click="avatarDialog = false">取 消</el-button>
  16.   <el-button type="primary" @click="avatarDialog = false">确 定</el-button>
  17.   </span>
  18.  </el-dialog>

然后的话,我用的是Vue

  1.  data: {
  2.          imageUrl: '',
  3.          avatarDialog: false,
  4.  },
  5.  methods: {
  6.   handleAvatarSuccess(res, file) {
  7.   this.imageUrl = URL.createObjectURL(file.raw);
  8.   this.$message.success("上传成功!刷新页面查看!")
  9.   },
  10.   beforeAvatarUpload(file) {
  11.          // 这里我也准备只接受jpg的格式储存所以我就直接用了官方提供的代码
  12.   const isJPG = file.type === 'image/jpeg';
  13.   const isLt2M = file.size / 1024 / 1024 < 2;
  14.          
  15.   if (!isJPG) {
  16.   this.$message.error('上传头像图片只能是 JPG 格式!');
  17.   }
  18.   if (!isLt2M) {
  19.   this.$message.error('上传头像图片大小不能超过 2MB!');
  20.   }
  21.   return isJPG && isLt2M;
  22.     }
  23.  }

前端不必多说叭,都是套的框架,然后后端使用的Springboot

这里用到的是commons -fileupload commons-io所以要先导入这两个依赖

  1.  <dependency>
  2.   <groupId>commons-fileupload</groupId>
  3.      <artifactId>commons-fileupload</artifactId>
  4.      <version>1.3.3</version>
  5.  </dependency>
  6.  <dependency>
  7.      <groupId>commons-io</groupId>
  8.      <artifactId>commons-io</artifactId>
  9.      <version>2.4</version>
  10.  </dependency>

用户头像图片的存储地址,为了不4所以我在application.yml添加了一个配置

 avatar-save-path: "/images/resource/UserAvatar/"

然后这里是CommonController

  1.  @Value("${avatar-save-path}")
  2.  private String avatarPath;
  3.  ​
  4.  @Autowired
  5.  UserServiceImpl userService;
  6.  ​
  7.  @PostMapping("/up/avatar")
  8.  public String upImg(MultipartFile file, HttpServletRequest req) throws IOException {
  9.      log.info("Updating the File:" + file.toString());
  10.      // 获取文件的原始名称
  11.   String originalFilename = file.getOriginalFilename();
  12.      // 获取原始文件的后缀,只不过我这里只接受jpg
  13.   String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
  14.   // 产生随机的UUID+文件后缀形成新的文件名(为了让图片没那么容易被覆盖)
  15.   String newName = UUID.randomUUID().toString() + suffix;
  16.  ​
  17.   String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
  18.   // 这里获取了session,因为当时项目访问这个接口不存在没登录的情况
  19.   User user = (User) req.getSession().getAttribute("user");
  20.   // 这里是生成了文件存储的路径
  21.   String basePath = path + avatarPath;
  22.      // 判断文件夹是否存在,不存在的话新建一个
  23.   File dir = new File(basePath);
  24.   if (!dir.exists()) {
  25.   dir.mkdirs();
  26.   }
  27.      // 因为一开始的文件存储在临时目录里,所以这里要转存到新的地方
  28.   file.transferTo(new File(basePath + newName));
  29.      // 将用户的头像地址改为新的地址
  30.   user.setAvatarUrl(avatarPath + newName);
  31.      // 这里是修改了数据库里用户的头像地址
  32.   userService.changeUser(user);
  33.      // 更新Session
  34.   req.getSession().setAttribute("user",user);
  35.   log.info("File: " + newName + " is saved in " + basePath);
  36.   log.info(user.getUsername() + " set avatar to " + basePath);
  37.      // 返回新的头像地址
  38.   return avatarPath + newName;
  39.  }

这是俺第一次写博客,可能会有些不对的地方或者可以优化的地方,希望大佬可以给我提提建议啥的,还有希望这篇文章可以帮助到跟我一样是萌新的小伙伴。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/393452
推荐阅读
相关标签
  

闽ICP备14008679号