前置知识:
在微人事中使用 FastDFS,首先准备三件事:
- 开启 FastDFS 服务(Tracker Server,Storage Server 以及 Nginx)
- 微人事中加入 FastDFS 相关依赖
<dependency>
<groupId>net.oschina.zcx7878</groupId>
<artifactId>fastdfs-client-java</artifactId>
<version>1.27.0.0</version>
</dependency>
- 准备一个配置文件 fastdfs-client.properties
- 开发一个文件上传工具类
public class FastDFSUtils {
private static StorageClient1 client1;
static {
try {
ClientGlobal.initByProperties("fastdfs-client.properties");
TrackerClient trackerClient = new TrackerClient();
TrackerServer trackerServer = trackerClient.getConnection();
client1 = new StorageClient1(trackerServer, null);
} catch (IOException e) {
e.printStackTrace();
} catch (MyException e) {
e.printStackTrace();
}
}
public static String upload(MultipartFile file) {
String oldName = file.getOriginalFilename();
try {
return client1.upload_file1(file.getBytes(), oldName.substring(oldName.lastIndexOf(".") + 1), null);
} catch (IOException e) {
e.printStackTrace();
} catch (MyException e) {
e.printStackTrace();
}
return null;
}
}
- 添加文件上传控制器
@PostMapping("/hr/userface")
public RespBean updateHrUserface(MultipartFile file, Integer id,Authentication authentication) {
String fileId = FastDFSUtils.upload(file);
String url = nginxHost + fileId;
if (hrService.updateUserface(url, id) == 1) {
Hr hr = (Hr) authentication.getPrincipal();
hr.setUserface(url);
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(hr, authentication.getCredentials(), authentication.getAuthorities()));
return RespBean.ok("更新成功!", url);
}
return RespBean.error("更新失败!");
}
扫码关注微信公众号 江南一点雨,回复 2TB,获取超 2TB Java 学习教程~