一、前言

前两篇整体上介绍了通过 Nginx 和 FastDFS 的整合来实现文件服务器。但是,在实际开发中对图片或文件的操作都是通过应用程序来完成的,因此,本篇将介绍 Spring Boot 整合 FastDFS 客户端来实现对图片/文件服务器的访问。

如果有不了解 FastDFS 的读者可以先浏览《FastDFS 环境搭建》《Nginx 整合 FastDFS 实现文件服务器》 来普及内容,或是另行查阅网上相关资料。

二、整合编码

# 2.1 添加依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-web</artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-test</artifactId>
  8. <scope>test</scope>
  9. </dependency>
  10. <dependency>
  11. <groupId>org.springframework.boot</groupId>
  12. <artifactId>spring-boot-devtools</artifactId>
  13. <optional>true</optional>
  14. <scope>true</scope>
  15. </dependency>
  16. <dependency>
  17. <groupId>com.github.tobato</groupId>
  18. <artifactId>fastdfs-client</artifactId>
  19. <version>1.26.3</version>
  20. </dependency>
  21. <dependency>
  22. <groupId>commons-io</groupId>
  23. <artifactId>commons-io</artifactId>
  24. <version>2.6</version>
  25. </dependency>
  26. <dependency>
  27. <groupId>org.springframework.boot</groupId>
  28. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  29. </dependency>

上边的 fastdfs-client 是并非 FastDFS Client 原作者编写的整合包,具体详情可以访问 https://github.com/tobato/FastDFS_Client

# 2.2 application.properties

  1. server.port=8080
  2. # fastDFS 配置
  3. fdfs.so-timeout=1501
  4. fdfs.connect-timeout=601
  5. fdfs.thumb-image.width=150
  6. fdfs.thumb-image.height=150
  7. fdfs.web-server-url=192.168.10.110/
  8. fdfs.tracker-list[0]=192.168.10.110:22122

# 2.3 后端代码

  • 加载 FastDFS 配置类:
  1. @Configuration
  2. @Import(FdfsClientConfig.class)
  3. // 解决jmx重复注册bean的问题
  4. @EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
  5. public class ComponetImport {
  6. // 导入依赖组件
  7. }
  • FastDFS 工具类:
  1. @Component
  2. public class FastDFSClient {
  3. private final Logger logger = LoggerFactory.getLogger(FastDFSClient.class);
  4. @Autowired
  5. private FastFileStorageClient storageClient;
  6. @Autowired
  7. private FdfsWebServer fdfsWebServer;
  8. /**
  9. * 上传文件
  10. * @param file 文件对象
  11. * @return 文件访问地址
  12. * @throws IOException
  13. */
  14. public String uploadFile(MultipartFile file) throws IOException {
  15. StorePath storePath = storageClient.uploadFile(file.getInputStream(),file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()),null);
  16. return getResAccessUrl(storePath);
  17. }
  18. /**
  19. * 上传文件
  20. * @param file 文件对象
  21. * @return 文件访问地址
  22. * @throws IOException
  23. */
  24. public String uploadFile(File file) throws IOException {
  25. FileInputStream inputStream = new FileInputStream (file);
  26. StorePath storePath = storageClient.uploadFile(inputStream,file.length(), FilenameUtils.getExtension(file.getName()),null);
  27. return getResAccessUrl(storePath);
  28. }
  29. /**
  30. * 将一段字符串生成一个文件上传
  31. * @param content 文件内容
  32. * @param fileExtension
  33. * @return
  34. */
  35. public String uploadFile(String content, String fileExtension) {
  36. byte[] buff = content.getBytes(Charset.forName("UTF-8"));
  37. ByteArrayInputStream stream = new ByteArrayInputStream(buff);
  38. StorePath storePath = storageClient.uploadFile(stream,buff.length, fileExtension,null);
  39. return getResAccessUrl(storePath);
  40. }
  41. // 封装图片完整URL地址
  42. private String getResAccessUrl(StorePath storePath) {
  43. String fileUrl = fdfsWebServer.getWebServerUrl() + storePath.getFullPath();
  44. return fileUrl;
  45. }
  46. /**
  47. * 下载文件
  48. * @param fileUrl 文件url
  49. * @return
  50. */
  51. public byte[] download(String fileUrl) {
  52. String group = fileUrl.substring(0, fileUrl.indexOf("/"));
  53. String path = fileUrl.substring(fileUrl.indexOf("/") + 1);
  54. byte[] bytes = storageClient.downloadFile(group, path, new DownloadByteArray());
  55. return bytes;
  56. }
  57. /**
  58. * 删除文件
  59. * @param fileUrl 文件访问地址
  60. * @return
  61. */
  62. public void deleteFile(String fileUrl) {
  63. if (StringUtils.isEmpty(fileUrl)) {
  64. return;
  65. }
  66. try {
  67. StorePath storePath = StorePath.praseFromUrl(fileUrl);
  68. storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
  69. } catch (FdfsUnsupportStorePathException e) {
  70. logger.warn(e.getMessage());
  71. }
  72. }
  73. }
  • controller 类:
  1. @RestController
  2. @RequestMapping("/fdfs")
  3. public class FastDFSController {
  4. @Autowired
  5. private FastDFSClient fdfsClient;
  6. /**
  7. * 文件上传
  8. * @param file
  9. * @return
  10. * @throws Exception
  11. */
  12. @RequestMapping("/upload")
  13. public Map<String,Object> upload(MultipartFile file) throws Exception{
  14. String url = fdfsClient.uploadFile(file);
  15. Map<String,Object> result = new HashMap<>();
  16. result.put("code", 200);
  17. result.put("msg", "上传成功");
  18. result.put("url", url);
  19. return result;
  20. }
  21. /**
  22. * 文件下载
  23. * @param fileUrl url 开头从组名开始
  24. * @param response
  25. * @throws Exception
  26. */
  27. @RequestMapping("/download")
  28. public void download(String fileUrl, HttpServletResponse response) throws Exception{
  29. byte[] data = fdfsClient.download(fileUrl);
  30. response.setCharacterEncoding("UTF-8");
  31. response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("test.jpg", "UTF-8"));
  32. // 写出
  33. ServletOutputStream outputStream = response.getOutputStream();
  34. IOUtils.write(data, outputStream);
  35. }
  36. }

# 2.4 前端页面

  1. <!DOCTYPE html>
  2. <html xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>文件上传</title>
  6. <link rel="stylesheet" th:href="@{/css/bootstrap.css}">
  7. <style>
  8. form {
  9. margin-top: 30px;
  10. }
  11. </style>
  12. </head>
  13. <body>
  14. <div class="container">
  15. <div class="row">
  16. <div class="col-md-4 col-sm-4"></div>
  17. <div class="col-md-4 col-sm-4">
  18. <h2> FastDFS 文件上传</h2>
  19. <form th:action="@{/fdfs/upload}" method="post" enctype="multipart/form-data">
  20. <div class="form-group">
  21. <input type="file" name="file" id="exampleInputFile">
  22. </div>
  23. <button type="submit" class="btn btn-default">上传</button>
  24. </form>
  25. </div>
  26. <div class="col-md-4 col-sm-4"></div>
  27. </div>
  28. </div>
  29. </body>
  30. </html>

三、测试

本篇只测试文件上传和访问的效果,演示图如下:

整合成功~~