Spring Boot 整合 FastDFS
引入pom依赖
<dependency> <groupId>com.github.tobato</groupId> <artifactId>fastdfs-client</artifactId> <version>1.26.2</version> </dependency>
配置类:
/** * @author 阮胜 * @EnableMBeanExport 用于解决jmx重复注册bean的问题 * @date 2018/8/16 18:22 */ @Configuration @Import(FdfsClientConfig.class) @EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING) public class ComponentImport { }
工具类:
/** * @author 阮胜 * @date 2018/8/16 17:33 */ @Component public class FastDFSWrapper { private static final String RESOURCE_URL = "http://192.168.186.128:22122/"; private final Logger logger = LoggerFactory.getLogger(FastDFSWrapper.class); @Autowired private FastFileStorageClient storageClient; /** * 上传文件 * * @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地址 * * @param storePath * @return */ private String getResAccessUrl(StorePath storePath) { return RESOURCE_URL + storePath.getFullPath(); } /** * 删除文件 * * @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) { logger.warn(e.getMessage()); } } }
控制层:
/** * @author 阮胜 * @date 2018/8/16 18:29 */ @RestController public class FileController { private final FastDFSWrapper fastDFSWrapper; public FileController(FastDFSWrapper fastDFSWrapper) { this.fastDFSWrapper = fastDFSWrapper; } @GetMapping("/upload/{str}") public String uploadStr(@PathVariable String str) { return fastDFSWrapper.uploadFile(str, "txt"); } }
application.yml 配置
fdfs:
so-timeout: 1501
connect-timeout: 601
thumb-image: #缩略图生成参数
width: 150
height: 150
tracker-list: #TrackerList参数,支持多个
- 192.168.186.128:22122
pool:
max-total: 150 #从池中借出的对象的最大数目
max-wait-millis: 100 #获取连接时的最大等待毫秒数100
server:
port: 9999
使用PostMan 测试:
测试结果:
这里的8080端口是服务器中 /etc/fdfs/client.conf 文件中的 http.tracker_server_port=8080 默认指定的