41.SpringBoot 结合 FastDFS

 

前置知识:

在微人事中使用 FastDFS,首先准备三件事:

  1. 开启 FastDFS 服务(Tracker Server,Storage Server 以及 Nginx)
  2. 微人事中加入 FastDFS 相关依赖
<dependency>
    <groupId>net.oschina.zcx7878</groupId>
    <artifactId>fastdfs-client-java</artifactId>
    <version>1.27.0.0</version>
</dependency>
  1. 准备一个配置文件 fastdfs-client.properties
  2. 开发一个文件上传工具类
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;
    }

}
  1. 添加文件上传控制器
@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 学习教程~

喜欢这篇文章吗?扫码关注公众号【江南一点雨】【江南一点雨】专注于 SPRING BOOT+微服务以及前后端分离技术,每天推送原创技术干货,关注后回复 JAVA,领取松哥为你精心准备的 JAVA 干货!

本文遵守 Attribution-NonCommercial 4.0 International 许可协议。 Attribution-NonCommercial 4.0 International