1、在 github 下载 fastdfs-client-java 源码:
git clone https://github.com/happyfish100/fastdfs-client-java.git
更多具体配置可参考 github 上的源码。
2、使用 maven 构建源码:
(1)构建源码前,需要先配置好 maven 的环境变量:
如上,当配置成功后,执行 mvn -v 可查看 maven 版本信息。
(2)进入刚下载的源码目录,执行 mvn clean install 进行构建:
当出现 build success 提示,表示已构建成功,构建后的 jar 包会存储在本地的仓库,比如我的是:
3、代码配置:
(1)pom.xml 依赖:
<!-- 引入fastdfs --> <dependency> <groupId>org.csource</groupId> <artifactId>fastdfs-client-java</artifactId> <version>1.29-SNAPSHOT</version> <!-- 因为 fastdfs-client-java 使用的也是org.slf4j包,为避免包冲突引起的错误,最好排除 --> <exclusions> <exclusion> <artifactId>slf4j-log4j12</artifactId> <groupId>org.slf4j</groupId> </exclusion> </exclusions> </dependency>
(2)在 resources 目录下新建 fdfs_client.conf 文件,内容如下:
connect_timeout = 10
network_timeout = 30
charset = UTF-8
http.tracker_http_port = 8080
http.anti_steal_token = no
http.secret_key = FastDFS1234567890
tracker_server = 192.168.229.142:22122
(3)FastDFSClientUtil 类:
package spcommon.util; import org.csource.fastdfs.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; @Component public class FastDFSClientUtil { private static Logger logger = LoggerFactory.getLogger(FastDFSClientUtil.class); private static final String CONFIG_FILENAME = "fdfs_client.conf"; // 加载文件 static { try { ClientGlobal.init(CONFIG_FILENAME); logger.info("初始化 Fastdfs Client 配置信息:{}", ClientGlobal.configInfo()); } catch (Exception e) { logger.error(e.toString(), e); } } /** * 上传文件 * @param fileContent * @param extName * @return * @throws Exception */ public String[] uploadFile(byte[] fileContent, String extName) { try { TrackerClient trackerClient = new TrackerClient(); TrackerServer trackerServer = trackerClient.getTrackerServer(); StorageServer storageServer = trackerClient.getStoreStorage(trackerServer); StorageClient storageClient = new StorageClient(trackerServer, storageServer); return storageClient.upload_file(fileContent, extName, null); } catch (Exception e) { logger.error(e.toString(), e); return null; } } /** * 下载文件 * @param groupName * @param fileId * @return */ public byte[] downloadFile(String groupName, String fileId) { try { TrackerClient trackerClient = new TrackerClient(); TrackerServer trackerServer = trackerClient.getTrackerServer(); StorageServer storageServer = trackerClient.getStoreStorage(trackerServer); StorageClient storageClient = new StorageClient(trackerServer, storageServer); byte[] fileByte = storageClient.download_file(groupName, fileId); return fileByte; } catch (Exception e) { logger.error(e.toString(), e); return null; } } /** * 删除文件 * @param groupName * @param remoteFilename * @return */ public int deleteFile(String groupName, String remoteFilename) { try { TrackerClient trackerClient = new TrackerClient(); TrackerServer trackerServer = trackerClient.getTrackerServer(); StorageServer storageServer = trackerClient.getStoreStorage(trackerServer); StorageClient storageClient = new StorageClient(trackerServer, storageServer); int i = storageClient.delete_file(groupName, remoteFilename); logger.info("delete file successfully!!!" + i); return 1; } catch (Exception e) { logger.error(e.toString(), e); return 0; } } }
(4)FdfsClientController:
package spapi.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import spcommon.util.FastDFSClientUtil; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.URLEncoder; @RestController public class FdfsClientController { private static Logger logger = LoggerFactory.getLogger(FdfsClientController.class); @Autowired FastDFSClientUtil fastDFSClientUtil; /** * 上传文件 * @param file * @return */ @RequestMapping("/uploadFile") public String uploadFile(@RequestParam("file") MultipartFile file) { try { // 获取原文件名 String origFileName = file.getOriginalFilename(); logger.info("原始文件名:{}", origFileName); // 获取扩展名 String extName = origFileName.substring(origFileName.lastIndexOf(".") + 1); logger.info("原始文件扩展名:{}", extName); // 获取文件存储路径 String[] uriArray = fastDFSClientUtil.uploadFile(file.getBytes(), extName); String groupName = uriArray[0]; String fileId = uriArray[1]; String uri = groupName + "/" + fileId; logger.info("返回的文件存储路径:{}", uri); return uri; } catch (Exception e) { logger.error(e.toString(), e); return null; } } /** * 下载文件 * @param groupName * @param fileId * @return */ @RequestMapping("/downloadFile") public void downloadFile(@RequestParam("groupName") String groupName, @RequestParam("fileId") String fileId, HttpServletResponse response) { try { // 获取文件名 int index = fileId.lastIndexOf("/"); String fileName = fileId.substring(index + 1); /** * 参数格式: * groupName: group1 * fileId: M00/00/00/wKjlj15o9rGAP5MkAACpl5L2fqw700.jpg */ byte[] fileByte = fastDFSClientUtil.downloadFile(groupName, fileId); InputStream inputStream = new ByteArrayInputStream(fileByte); response.setHeader("content-type", "application/octet-stream"); response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); byte[] buff = new byte[1024]; BufferedInputStream bis = new BufferedInputStream(inputStream); OutputStream os = response.getOutputStream(); int i = bis.read(buff); while (i != -1) { os.write(buff, 0, buff.length); os.flush(); i = bis.read(buff); } os.close(); bis.close(); logger.info("Download successfully!"); } catch (Exception e) { logger.error(e.toString(), e); } } /** * 删除文件 * @param groupName * @param fileId * @return */ @RequestMapping("/deleteFile") public String deleteFile(@RequestParam("groupName") String groupName, @RequestParam("fileId") String fileId) { try { /** * 参数格式: * groupName: group1 * fileId: M00/00/00/wKjlj15o9rGAP5MkAACpl5L2fqw700.jpg */ int i = fastDFSClientUtil.deleteFile(groupName, fileId); return (i > 0) ? "删除文件成功" : "删除文件失败"; } catch (Exception e) { logger.error(e.toString(), e); return null; } } }
注:fasdfs 上传时不能自定义文件名,如果想使用自定义的文件名,通常是当服务器返回文件名后,再自定义一个与之对应的文件名保存到数据库。