SpringBoot整合FastDFS笔记

桃扇骨 2024-03-16 21:56 190阅读 0赞

SpringBoot整合FastDFS笔记

  1. FastDFS是国人余庆开发的一个的分布式存储系统,github地址是https://github.com/happyfish100/fastdfs
  2. FastDFS的特性:
  3. 1、分组存储,灵活简洁、对等结构,不存在单点
  4. 2 文件IDFastDFS生成,作为文件访问凭证。FastDFS不需要传统的name server
  5. 3、和流行的web server无缝衔接,FastDFS已提供apachenginx扩展模块
  6. 4、大、中、小文件均可以很好支持,支持海量小文件存储
  7. 5 支持多块磁盘,支持单盘数据恢复
  8. 6 支持相同文件内容只保存一份,节省存储空间
  9. 7 存储服务器上可以保存文件附加属性
  10. 8 下载文件支持多线程方式,支持断点续传
  11. FastDFS部署教程可以参考
  12. https://www.jb51.net/article/251253.htm

springboot整合fastDFS的物料准备:

1.java项目配置fastdfs

2.定义工具类

3.测试使用效果

java项目配置fastdfs

引入fastdfs-client相关依赖

  1. <dependency>
  2. <groupId>cn.hutool</groupId>
  3. <artifactId>hutool-all</artifactId>
  4. <version>5.7.8</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>com.github.tobato</groupId>
  8. <artifactId>fastdfs-client</artifactId>
  9. <version>1.26.7</version>
  10. </dependency>

配置项目yml文件

  1. fdfs:
  2. so-timeout: 5000 # 读取时间
  3. connect-timeout: 5000 #连接超时
  4. # 生成缩略图参数
  5. thumb-image:
  6. width: 50
  7. height: 50
  8. # 支持配置多个存储节点
  9. tracker-list:
  10. - 10.1.5.212:22122

启动类配置

  1. package com.example.demo;
  2. import com.github.tobato.fastdfs.FdfsClientConfig;
  3. import org.mybatis.spring.annotation.MapperScan;
  4. import org.springframework.boot.SpringApplication;
  5. import org.springframework.boot.autoconfigure.SpringBootApplication;
  6. import org.springframework.context.annotation.Import;
  7. @Import({
  8. FdfsClientConfig.class,cn.hutool.extra.spring.SpringUtil.class})
  9. @MapperScan(basePackages = {
  10. "com.example.demo.orm.dao"})
  11. @SpringBootApplication
  12. public class DemoApplication {
  13. public static void main(String[] args) {
  14. SpringApplication.run(DemoApplication.class, args);
  15. }
  16. }

定义fdfs工具类

  1. package com.example.demo.util;
  2. import cn.hutool.core.io.file.FileNameUtil;
  3. import cn.hutool.core.util.StrUtil;
  4. import com.github.tobato.fastdfs.domain.fdfs.StorePath;
  5. import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
  6. import com.github.tobato.fastdfs.service.FastFileStorageClient;
  7. import lombok.extern.slf4j.Slf4j;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.stereotype.Component;
  10. import org.springframework.web.multipart.MultipartFile;
  11. import java.io.*;
  12. import java.nio.charset.StandardCharsets;
  13. @Component
  14. @Slf4j
  15. public class FdfsTools {
  16. @Autowired
  17. private FastFileStorageClient fastFileStorageClient;
  18. /**
  19. * 文件上传, byte 流类型
  20. *
  21. * @param bytes 文件字节
  22. * @param fileSize 文件大小
  23. * @param extension 文件扩展名
  24. * @return fastDfs路径
  25. */
  26. public String uploadFile(byte[] bytes, long fileSize, String extension) {
  27. ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
  28. StorePath storePath = fastFileStorageClient.uploadFile(
  29. byteArrayInputStream,
  30. fileSize,
  31. extension,
  32. null);
  33. return storePath.getFullPath();
  34. }
  35. /**
  36. * MultipartFile类型的文件上传ַ
  37. *
  38. * @param file
  39. * @return
  40. * @throws IOException
  41. */
  42. public String uploadFile(MultipartFile file) throws IOException {
  43. StorePath storePath = fastFileStorageClient.uploadFile(
  44. file.getInputStream(),
  45. file.getSize(),
  46. FileNameUtil.getSuffix(file.getOriginalFilename()),
  47. null);
  48. return storePath.getFullPath();
  49. }
  50. /**
  51. * 普通文件上传
  52. *
  53. * @param file
  54. * @return
  55. * @throws IOException
  56. */
  57. public String uploadFile(File file) throws FileNotFoundException {
  58. FileInputStream inputStream = new FileInputStream(file);
  59. StorePath path = fastFileStorageClient.uploadFile(
  60. inputStream,
  61. file.length(),
  62. FileNameUtil.getSuffix(file),
  63. null);
  64. return path.getFullPath();
  65. }
  66. public String createFileAndUpload(String sourceFilePath) throws Exception {
  67. File file = new File(sourceFilePath);
  68. return uploadFile(file);
  69. }
  70. /**
  71. * 带输入流形式的文件上传
  72. *
  73. * @param inputStream
  74. * @param size
  75. * @param fileName
  76. * @return
  77. */
  78. public String uploadFile(InputStream inputStream, long size, String fileName) {
  79. StorePath path = fastFileStorageClient.uploadFile(inputStream, size, fileName, null);
  80. return path.getFullPath();
  81. }
  82. /**
  83. * 将一段文本文件写到fastdfs的服务器上
  84. *
  85. * @param content
  86. * @param fileExtension
  87. * @return
  88. */
  89. public String uploadFile(String content, String fileExtension) {
  90. byte[] buff = content.getBytes(StandardCharsets.UTF_8);
  91. ByteArrayInputStream stream = new ByteArrayInputStream(buff);
  92. StorePath path = fastFileStorageClient.uploadFile(stream, buff.length, fileExtension, null);
  93. return path.getFullPath();
  94. }
  95. /**
  96. * 下载文件
  97. *
  98. * @param fileUrl 文件URL
  99. * @return 文件字节
  100. */
  101. public byte[] downloadFile(String fileUrl) {
  102. String group = fileUrl.substring(0, fileUrl.indexOf("/"));
  103. String path = fileUrl.substring(fileUrl.indexOf("/") + 1);
  104. DownloadByteArray downloadByteArray = new DownloadByteArray();
  105. log.info("fdfs下载文件的group:{}",group);
  106. log.info("fdfs下载文件的path:{}",path);
  107. return fastFileStorageClient.downloadFile(group, path, downloadByteArray);
  108. }
  109. public void deleteFile(String fileUrl) {
  110. if (StrUtil.isBlank(fileUrl)) {
  111. return;
  112. }
  113. try {
  114. StorePath storePath = StorePath.parseFromUrl(fileUrl);
  115. fastFileStorageClient.deleteFile(storePath.getGroup(), storePath.getPath());
  116. } catch (Exception e) {
  117. log.error("", e);
  118. }
  119. }
  120. }

测试使用效果

  1. package com.example.demo;
  2. import cn.hutool.core.io.IoUtil;
  3. import cn.hutool.core.io.file.FileNameUtil;
  4. import com.example.demo.util.FdfsTools;
  5. import lombok.extern.slf4j.Slf4j;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.web.bind.annotation.*;
  8. import org.springframework.web.multipart.MultipartFile;
  9. import org.springframework.web.multipart.MultipartHttpServletRequest;
  10. import javax.servlet.ServletOutputStream;
  11. import javax.servlet.http.HttpServletResponse;
  12. import java.io.ByteArrayInputStream;
  13. import java.io.IOException;
  14. import java.nio.charset.StandardCharsets;
  15. import java.util.ArrayList;
  16. import java.util.List;
  17. import java.util.Map;
  18. @Slf4j
  19. @RestController
  20. public class FdfsTestController {
  21. @Autowired
  22. private FdfsTools fdfsTools;
  23. /**
  24. * 下载fastdfs里的文件
  25. * http://localhost:8621/mybatis/download?fullPath=group1/M00/64/AF/CgEF1GSSpkGACiJlAAvqH-Poukk892.jpg
  26. * @param fullPath
  27. * @param response
  28. * @throws IOException
  29. */
  30. @GetMapping("/download")
  31. public void download(@RequestParam String fullPath, HttpServletResponse response) throws IOException {
  32. byte[] bytes = fdfsTools.downloadFile(fullPath);
  33. String name = FileNameUtil.getName(fullPath);
  34. System.out.println(name);
  35. response.setHeader("Content-Disposition",
  36. "attachment;filename=" + new String(name.getBytes(), StandardCharsets.ISO_8859_1));
  37. ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
  38. ServletOutputStream ops = response.getOutputStream();
  39. IoUtil.copy(inputStream, ops);
  40. IoUtil.closeIfPosible(inputStream);
  41. IoUtil.closeIfPosible(ops);
  42. }
  43. /**
  44. * 前端单文件上传 form-data形式参数, 传1个 MultipartFile类型,参数名file
  45. * @param multipartFile
  46. * @return
  47. * @throws IOException
  48. */
  49. @PostMapping("/uploadOne")
  50. public String upload(@RequestPart("file") MultipartFile multipartFile) throws IOException {
  51. System.out.println(multipartFile.getOriginalFilename());
  52. String s = fdfsTools.uploadFile(multipartFile);
  53. return "fullPath=" + s;
  54. }
  55. /**
  56. * 前端多文件上传 form-data形式参数 传多个MultipartFile类型,参数名随意
  57. * @param request
  58. * @return
  59. * @throws IOException
  60. */
  61. @PostMapping("/uploadBatch")
  62. public List<String> uploadBatch(MultipartHttpServletRequest request) throws IOException {
  63. List<String> result = new ArrayList<>();
  64. Map<String, MultipartFile> fileMap = request.getFileMap();
  65. for (MultipartFile multipartFile : fileMap.values()) {
  66. if (!multipartFile.isEmpty()){
  67. System.err.println(multipartFile.getOriginalFilename());
  68. String s = fdfsTools.uploadFile(multipartFile);
  69. result.add("fullPath=" +s);
  70. }
  71. }
  72. return result;
  73. }
  74. /**
  75. * 将一段文本文件写到fastdfs的服务器上
  76. * @param content
  77. * @return fullPath=group1/M00/64/AF/CgEF1GSSqdGAHrO4AAAAD0mMR3c910.txt
  78. */
  79. @PostMapping("/saveTxtToFdfs")
  80. public String saveTxtToFdfs(@RequestParam String content){
  81. String s = fdfsTools.uploadFile(content, "txt");
  82. return "fullPath=" +s;
  83. }
  84. /**
  85. * 删除FastDfs上的文件
  86. * http://localhost:8621/mybatis/delFile?fullPath=group1/M00/64/AF/CgEF1GSSpnKAY3CiAAvea9v85c0615.jpg
  87. * @param fullPath
  88. * @return
  89. */
  90. @DeleteMapping("/delFile")
  91. public String deleteFastDfsFile(@RequestParam String fullPath){
  92. fdfsTools.deleteFile(fullPath);
  93. return "ok!";
  94. }
  95. }

测试上传单个文件
在这里插入图片描述
测试上传多个文件
在这里插入图片描述
测试删除FastDFS里已上传的文件
在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,190人围观)

还没有评论,来说两句吧...

相关阅读

    相关 springboot整合fastdfs

    在项目开发中经常会碰到做文件上传的功能,一般来说,文件上传的步骤就那么几步,前台通过提交一个选中的文件,后端对文件做处理然后将文件上传至指定的地址,这个地址是一个真实的物理存储