由於咱們項目用的是Springboot 2.0以上的,因此跟Springboot 1.x的會有一些不一樣。git
pomgithub
<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.服務器
配置文件app
@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 { }
文件操做工具類socket
@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,獲得正確的返回結果測試
在瀏覽器中訪問該圖片this
基本操做已經成功完成了,該圖片也被存儲到了多臺文件服務器中。對象