当前位置: 首页 > article >正文

springboot3.x整合fastdfs

一、环境要求

  • JDK 17+(Spring Boot 3.x 强制要求)

  • Spring Boot 3.2.6(或其他 3.x 版本)

  • FastDFS 服务端(Tracker + Storage,已部署并正常运行)

二、依赖配置

1. 添加 FastDFS 客户端依赖

 <!-- FastDFS -->
        <dependency>
            <groupId>com.github.tobato</groupId>
            <artifactId>fastdfs-client</artifactId>
            <version>1.27.2</version>
        </dependency>

2. 配置 FastDFS 连接

在 application.yml 中添加配置:

fdfs:
  connect-timeout: 600    # 连接超时(毫秒)
  so-timeout: 1500        # 通信超时(毫秒)
  tracker-list: 192.168.1.100:22122  # Tracker 服务器地址(多个用逗号分隔)
  fileUrl: http://192.168.1.100:8888/  # 文件访问的 HTTP 地址

三、核心代码实现

package ym.controller;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import ym.vo.BaseResult;
import ym.vo.CodeEnum;

import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * fastdfs文件接口
 */
@RestController
@RequestMapping("/file")
@CrossOrigin
public class FileController {
    @Autowired
    private FastFileStorageClient fastFileStorageClient;
    @Value("${fdfs.fileUrl}")
    private String fileUrl; // Nginx访问FastDFS中文件的路径

    /**
     * fastdfs上传文件
     *
     * @param file 文件
     * @return
     * @throws IOException
     */
    @PostMapping("/fastdfs/upload")
    public BaseResult<String> fastdfsUpload(MultipartFile file) throws IOException {
        // MultipartFile对象不能再服务间传递,必须转为byte数组
        byte[] fileBytes = file.getBytes();
        String fileName = file.getOriginalFilename();
        String imageUrl = "";
        if (fileBytes.length != 0) {
            try {
                // 1.将文件字节数组转为输入流
                InputStream inputStream = new ByteArrayInputStream(fileBytes);
                // 2.获取文件的后缀名
                String fileSuffix = fileName.substring(fileName.lastIndexOf(".") + 1);
                // 3.上传文件
                StorePath storePath = fastFileStorageClient.uploadFile(inputStream, inputStream.available(), fileSuffix, null);
                // 4.返回图片路径
                imageUrl = fileUrl + "/" + storePath.getFullPath();

            } catch (IOException ioException) {
                return new BaseResult<>(CodeEnum.FILE_FASTDFS_UPLOAD_ERROR.getCode(), CodeEnum.FILE_FASTDFS_UPLOAD_ERROR.getMessage(), null);
            }
        } else {
            return new BaseResult<>(CodeEnum.FILE_FASTDFS_UPLOAD_ERROR.getCode(), CodeEnum.FILE_FASTDFS_UPLOAD_ERROR.getMessage(), null);
        }
        return BaseResult.ok(imageUrl);
    }

    /**
     * fastdfs删除文件
     *
     * @param filePath 文件路径
     * @return
     */
    @DeleteMapping("/fastdfs/delete")
    public BaseResult fastdfsDelete(String filePath) {
        fastFileStorageClient.deleteFile(filePath);
        return BaseResult.ok();
    }

    /**
     * fastdfs下载文件
     *
     * @param filePath 文件路径
     * @return
     */
    @GetMapping("/fastdfs/download")
    public void fastdfsDownLoad(String filePath) throws IOException {
        //http://118.31.60.184:8888/group1/M00/00/00/rBoX5mR0ulSAIukOAASzmDL13HM352.jpg
        byte[] bytes = null;
        try {
            //返回"/"第三次出现的位置
            int index1 = StringUtils.ordinalIndexOf(filePath, "/", 3);
            int index2 = StringUtils.ordinalIndexOf(filePath, "/", 4);
            String group = filePath.substring(index1 + 1, index2);
            String filepath = filePath.substring(filePath.lastIndexOf(group + "/") + 7);
            DownloadByteArray callback = new DownloadByteArray();
            bytes = fastFileStorageClient.downloadFile(group, filepath, callback);

            //文件输出流
            FileOutputStream fileOutputStream = new FileOutputStream("D:\\A多媒体\\图库\\fastdfs");
            fileOutputStream.write(bytes);
            fileOutputStream.flush();
            fileOutputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

四、配置文件

package ym.config;

import com.github.tobato.fastdfs.FdfsClientConfig;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableMBeanExport;
import org.springframework.context.annotation.Import;
import org.springframework.jmx.support.RegistrationPolicy;

/**
 * fastdfs配置文件
 */
@Configuration
@Import(FdfsClientConfig.class)
// 解决jmx重复注册bean的问题
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
public class FastDFSConfig {
}

五、上传接口测试 


http://www.kler.cn/a/557837.html

相关文章:

  • Wireshark详解
  • cs106x-lecture14(Autumn 2017)-SPL实现
  • Python Matplotlib图形美化指南
  • C#DevExpress使用GridLookUpEdit实现订单明细选择商品
  • vue3 文件类型传Form Data数据格式给后端
  • 《[含文档+PPT+源码等]精品基于Python实现的Django中药材在线学习系统的设计与实现
  • 和平之翼代码生成器 SHCEU 版 4.0.0RC6 千年隼介绍二
  • 通过wifi无线方式,通过adb命令连接手机,用来传输文件和安装app
  • Open WebUI选择模型为空,解决办法(for DeepSeek)
  • Ubuntu 下 nginx-1.24.0 源码分析 - ngx_atoi 函数
  • 嵌入式之宏定义编程机制
  • 代码随想录算法训练营第十一天|150. 逆波兰表达式求值|239. 滑动窗口最大值|347.前 K 个高频元素
  • 在WPS中设置word的页码不从第一页开始,从指定页开始插入页码
  • Ops 详解:从 DevOps 到 SecOps,探索网络安全与运维的核心概念
  • [STM32 - 野火] - - - 固件库学习笔记 - - - 十六.在SRAM中调试代码
  • 跟着 Lua 5.1 官方参考文档学习 Lua (6)
  • 使用Docker Desktop部署GitLab
  • CUDA兼容NVIDA版本关系
  • 《Keras 2 :使用 RetinaNet 进行对象检测》:此文为AI自动翻译
  • LLaMA-Factory|微调大语言模型初探索(3),qlora微调deepseek记录