<dependency> <groupId>com.github.tobato</groupId> <artifactId>fastdfs-client</artifactId> <version>1.26.2</version> </dependency>
fdfs: soTimeout: 1500 #socket连接超时时长 connectTimeout: 600 #连接tracker服务器超时时长 resHost: 192.168.5.129 storagePort: 8889 thumbImage: #缩略图生成参数,可选 width: 150 height: 150 trackerList: #TrackerList参数,支持多个,我这里只有一个,如果有多个在下方加- x.x.x.x:port - 192.168.5.129:22122
注意:我这里存储服务端口用的8889,一般为8888
@Component public class AppConfig { @Value("${fdfs.resHost}") private String resHost; @Value("${fdfs.storagePort}") private String storagePort; public String getResHost() { return resHost; } public void setResHost(String resHost) { this.resHost = resHost; } public String getStoragePort() { return storagePort; } public void setStoragePort(String storagePort) { this.storagePort = storagePort; } }
@Configuration @Import(FdfsClientConfig.class) // 解决jmx重复注册bean的问题 @EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING) public class FastClientImporter { }
文件操作工具类:
@Slf4j @Component public class FastDFSClientWrapper { @Autowired private FastFileStorageClient storageClient; @Autowired private AppConfig appConfig; // 项目参数配置 /** * 上传文件 * @param file 文件对象 * @return 文件访问地址 * @throws IOException */ public String uploadFile(MultipartFile file) throws IOException { StorePath storePath = storageClient.uploadFile(file.getInputStream(),file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()),null); return getResAccessUrl(storePath); } /** * 将一段字符串生成一个文件上传 * @param content 文件内容 * @param fileExtension * @return */ public String uploadFile(String content, String fileExtension) { byte[] buff = content.getBytes(Charset.forName("UTF-8")); ByteArrayInputStream stream = new ByteArrayInputStream(buff); StorePath storePath = storageClient.uploadFile(stream,buff.length, fileExtension,null); return getResAccessUrl(storePath); } // 封装图片完整URL地址 private String getResAccessUrl(StorePath storePath) { String fileUrl = "http://" + appConfig.getResHost() + ":" + appConfig.getStoragePort() + "/" + storePath.getFullPath(); return fileUrl; } /** * 删除文件 * @param fileUrl 文件访问地址 * @return */ public void deleteFile(String fileUrl) { if (StringUtils.isEmpty(fileUrl)) { return; } try { StorePath storePath = StorePath.praseFromUrl(fileUrl); storageClient.deleteFile(storePath.getGroup(), storePath.getPath()); } catch (FdfsUnsupportStorePathException e) { log.warn(e.getMessage()); } } }
测试Controller:
@RestController public class FastDFSController { @Autowired private FastDFSClientWrapper dfsClient; @PostMapping("/files-anon/fdfsupload") public String upload(@RequestParam("file") MultipartFile file) throws Exception { String imgUrl = dfsClient.uploadFile(file); return imgUrl; } }
经过Postman访问该API,得到正确的返回结果
在浏览器中访问该图片
基本操作已经成功完成了,该图片也被存储到了多台文件服务器中。