1. 在配置文件中指定外部环境, 注入到代码中
头像上传路径, 若不存在, 会根据该路径创建指定路径文件夹
1
2
|
upload: path: D:\\upload\headImgs |
创建类 FileUtils 并读取配置文件中的值
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
@Component @ConfigurationProperties (prefix = "upload" ) @Data public class FileUtils { private String path; public File getPath() { // 构建上传文件的存放 "文件夹" 路径 String fileDirPath = new String(path); File fileDir = new File(fileDirPath); if (!fileDir.exists()) { // 递归生成文件夹 fileDir.mkdirs(); } return fileDir; } public boolean del(String filename) { File file = new File(path + File.separator + filename); return file.delete(); } public boolean del(String path, String filename) { return new File(path + File.separator + filename).delete(); } } |
2. 设置上传文件的限制配置
1
2
3
4
5
|
spring: servlet: multipart: max-request-size: 10MB # 上传文件的最大值 max-file-size: 5MB # 单个文件上传的最大值 |
3. 设置外部路径映射到url
创建config类
注意: 映射路径时, 最后面一定要加 / (File.separator)
1
2
3
4
5
6
7
8
9
10
11
12
|
@Configuration public class WebMvcConfig extends WebMvcConfigurationSupport { @Autowired private FileUtils fileUtils; @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { // 加入头像文件夹映射 可通过 localhost:7188/headimage/.... 访问到指定位置的图片 registry.addResourceHandler( "/static/**" ).addResourceLocations( "classpath:/static/" ); // 默认头像 registry.addResourceHandler( "/headimage/**" ).addResourceLocations( "file:" +fileUtils.getPath().getPath()+ File.separator); super .addResourceHandlers(registry); } } |
注意:
- 此时映射了两个路径
- 外部环境的路径static目录下的路径(该路径用于存放一张默认图片随意一张, 作为默认头像 可命名为 default.jpg)
4. 用户实体类中 加入 image 字段
该字段默认值为 ‘static/default.jpg’ 即为用户的默认头像
作用: 存放图片的相对路径
5. Controller层编写
1
2
3
4
5
6
7
8
9
|
@RestController @RequestMapping ( "operate/User" ) public class UserController extends BaseController<UserService> { @ApiOperation ( "修改(可以修改头像和邮箱)" ) @PutMapping public R modify(MultipartFile headImg, String email){ return baseService.modify(headImg, email); } } |
6. Service层编写
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
|
public interface UserService extends IService<User> { R modify(MultipartFile headImg, String email); } @Slf4j @Service public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService { @Autowired private FileUtils fileUtils; /** * 获取当前用户名 * * @return */ private String getCurrentuserName() { // ... return username; } /** * 获取当前用户 * * @return */ public User getCurrentuser() { // ... return user; } @Override public R modify(MultipartFile headImg, String email) { // 校验图片格式 if (!imageTypeRight(headImg)) return R.fail( "图片格式不正确" ); // 获取上传文件后的路径 String path = uploadFile(headImg); User currentuser = getCurrentuser(); // 删除之前的头像(如果是默认头像不删除) String image = currentuser.getImage(); if (!image.equals( "static/default.png" )) { if (!fileUtils.del(image.substring(path.indexOf( "/" ) + 1 ))) { log.info( "修改头像时, 原来的头像删除失败" ); } else { log.info( "修改头像时, 原来的头像删除成功" ); } } // 修改数据库中头像的路径信息 和 邮箱 update(Wrappers.<User>lambdaUpdate() .set(User::getEmail, email) .set(User::getImage, path) .eq(User::getUsername, currentuser.getUsername())); // 该路径为图片相对路径 可放在url中的服务后面 进行访问 // 比如: http://localhost:9000/cloudos-opt/headimage/01c8806dc26d45539b53c22c766cd250.jpg // http://localhost:9000/cloudos-opt/static/default.png return R.success( null , path); } /** * 验证图片的格式 * * @param file 图片 * @return */ private boolean imageTypeRight(MultipartFile file) { // 首先校验图片格式 List<String> imageType = Lists.newArrayList( "jpg" , "jpeg" , "png" , "bmp" , "gif" ); // 获取文件名,带后缀 String originalFilename = file.getOriginalFilename(); // 获取文件的后缀格式 String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf( "." ) + 1 ).toLowerCase(); //不带 . if (!imageType.contains(fileSuffix)) return false ; return true ; } /** * 上传文件 * * @param file * @return 返回路径 */ public String uploadFile(MultipartFile file) { String originalFilename = file.getOriginalFilename(); String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf( "." ) + 1 ).toLowerCase(); // 只有当满足图片格式时才进来,重新赋图片名,防止出现名称重复的情况 String newFileName = UUID.randomUUID().toString().replaceAll( "-" , "" ) + "." + fileSuffix; // 该方法返回的为当前项目的工作目录,即在哪个地方启动的java线程 File fileTransfer = new File(fileUtils.getPath(), newFileName); try { file.transferTo(fileTransfer); log.info( "头像上传: " + fileTransfer.getPath()); } catch (IOException e) { e.printStackTrace(); } // 将图片相对路径返回给前端 return "headimage/" + newFileName; } } |
7. 测试
获取默认头像的路径url为
http://localhost:8080/{spring-application-name}/static/default.jpg
修改头像
修改完成后, 返回相对路径
访问修改后的头像
带上相对路径在url上直接可以访问
到此这篇关于Springboot 上传文件或头像(MultipartFile、transferTo)的文章就介绍到这了,更多相关Springboot 上传文件或头像内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.csdn.net/HD243608836/article/details/129998984