赞
踩
最近一直在做一个背单词的小项目练手,准备着加入个新功能,想了很多种办法,本来准备利用sm.ms图床,把用户头像上传到图床然后返回链接把链接存到数据库里,后来想了想,感觉用户的头像存在那不太好,于是还是决定把用户头像存储在项目里的一个文件夹好了。
ElementUI提供了upload的组件 组件 | Element官方文档 对于我这种没啥艺术细胞的人就只能用人家提供的框架拉(不过说实话我觉得element的组件还是都挺好看的捏)我们这里就直接使用这个组件,然后我这里就直接使用自动上传了。
我想实现的功能就是用户头像下面有个按钮,点击会弹出一个窗口,是用来上传用户头像的,所以还需要用到Dialog的组件,下面是我的HTML部分代码
- <el-button plain @click="avatarDialog = true">更换头像</el-button>
-
- <el-dialog title="更换头像"
- :visible.sync="avatarDialog"
- width="80%">
- <el-upload class="avatar-uploader"
- action="/api/up/avatar"
- :show-file-list="false"
- :on-success="handleAvatarSuccess"
- :before-upload="beforeAvatarUpload">
- <img v-if="imageUrl" :src="imageUrl" class="avatar">
- <i v-else class="el-icon-plus avatar-uploader-icon"></i>
- </el-upload>
- <span slot="footer" class="dialog-footer">
- <el-button @click="avatarDialog = false">取 消</el-button>
- <el-button type="primary" @click="avatarDialog = false">确 定</el-button>
- </span>
- </el-dialog>

然后的话,我用的是Vue
- data: {
- imageUrl: '',
- avatarDialog: false,
- },
- methods: {
- handleAvatarSuccess(res, file) {
- this.imageUrl = URL.createObjectURL(file.raw);
- this.$message.success("上传成功!刷新页面查看!")
- },
- beforeAvatarUpload(file) {
- // 这里我也准备只接受jpg的格式储存所以我就直接用了官方提供的代码
- 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;
- }
- }

前端不必多说叭,都是套的框架,然后后端使用的Springboot
这里用到的是commons -fileupload 和commons-io所以要先导入这两个依赖
- <dependency>
- <groupId>commons-fileupload</groupId>
- <artifactId>commons-fileupload</artifactId>
- <version>1.3.3</version>
- </dependency>
- <dependency>
- <groupId>commons-io</groupId>
- <artifactId>commons-io</artifactId>
- <version>2.4</version>
- </dependency>
用户头像图片的存储地址,为了不4所以我在application.yml添加了一个配置
avatar-save-path: "/images/resource/UserAvatar/"
然后这里是CommonController
- @Value("${avatar-save-path}")
- private String avatarPath;
-
- @Autowired
- UserServiceImpl userService;
-
- @PostMapping("/up/avatar")
- public String upImg(MultipartFile file, HttpServletRequest req) throws IOException {
- log.info("Updating the File:" + file.toString());
- // 获取文件的原始名称
- String originalFilename = file.getOriginalFilename();
- // 获取原始文件的后缀,只不过我这里只接受jpg
- String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
- // 产生随机的UUID+文件后缀形成新的文件名(为了让图片没那么容易被覆盖)
- String newName = UUID.randomUUID().toString() + suffix;
-
- String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
- // 这里获取了session,因为当时项目访问这个接口不存在没登录的情况
- User user = (User) req.getSession().getAttribute("user");
- // 这里是生成了文件存储的路径
- String basePath = path + avatarPath;
- // 判断文件夹是否存在,不存在的话新建一个
- File dir = new File(basePath);
- if (!dir.exists()) {
- dir.mkdirs();
- }
- // 因为一开始的文件存储在临时目录里,所以这里要转存到新的地方
- file.transferTo(new File(basePath + newName));
- // 将用户的头像地址改为新的地址
- user.setAvatarUrl(avatarPath + newName);
- // 这里是修改了数据库里用户的头像地址
- userService.changeUser(user);
- // 更新Session
- req.getSession().setAttribute("user",user);
- log.info("File: " + newName + " is saved in " + basePath);
- log.info(user.getUsername() + " set avatar to " + basePath);
- // 返回新的头像地址
- return avatarPath + newName;
- }

这是俺第一次写博客,可能会有些不对的地方或者可以优化的地方,希望大佬可以给我提提建议啥的,还有希望这篇文章可以帮助到跟我一样是萌新的小伙伴。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。