FastDFS与Springboot集成

本文详细介绍如何在SpringBoot项目中集成FastDFS文件系统,包括添加依赖、配置参数及使用方法,并提供一个实用的文件上传工具类。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

整合到Springboot项目流程

注意:必须是Springboot项目

1、添加pom依赖

<dependency>
    <groupId>com.github.tobato</groupId>
    <artifactId>fastdfs-client</artifactId>
    <version>1.25.2-RELEASE</version>
</dependency>

2、将Fdfs配置引入项目

我将注解配置加在springboot的入口类中:@Import(FdfsClientConfig.class)

@Import(FdfsClientConfig.class)
@SpringBootApplication
public class JingtongApplication {

    public static void main(String[] args) {
        SpringApplication.run(JingtongApplication.class, args);
    }
}

3、在spring配置文件中加入fdfs相关配置

根据项目当中使用配置文件类型(.yml和.properties选择其中一个),加入相应的配置。

application.yml

fdfs:
  soTimeout: 1500
  connectTimeout: 600
  thumbImage:             #缩略图生成参数
    width: 150
    height: 150
  trackerList:            #TrackerList参数,支持多个
    - 192.168.0.201:22122
    - 192.168.0.202:22122 

application.properties
fdfs.soTimeout=1500
fdfs.connectTimeout=600
fdfs.thumbImage.width=150
fdfs.thumbImage.height=150
fdfs.trackerList[0]=192.168.0.201:22122
fdfs.trackerList[1]=192.168.0.202:22122

4、在项目中使用

客户端主要包括以下接口:

TrackerClient - TrackerServer接口

GenerateStorageClient - 一般文件存储接口 (StorageServer接口)

FastFileStorageClient - 为方便项目开发集成的简单接口(StorageServer接口)

AppendFileStorageClient - 支持文件续传操作的接口 (StorageServer接口)

笔者在前一个项目当中将fdfs主要用于图片存储,基于FastFileStorageClient接口和springmvc提供的MultipartFile接口封装了一个简单的工具类,方便全局管理与调用。如下所示:

@Component
public class FastDFSClientWrapper {
    private final Logger logger = LoggerFactory.getLogger(FastDFSClientWrapper.class);
    @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 = AppConstants.HTTP_PRODOCOL + appConfig.getResHost()
                + ":" + appConfig.getFdfsStoragePort() + "/" + 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) {
            logger.warn(e.getMessage());
        }
    }

    /**
     * 文件下载方式一
     * @param response
     */
    public void downloadFile1(HttpServletResponse response){
        byte[] b = fastFileStorageClient.downloadFile("group1", "M00/83/F7/wKiNgVplw4GAKqNnAANbI4wCqFY733.jpg", new DownloadByteArray());
        ByteArrayInputStream bais = new ByteArrayInputStream(b);
        try {
            String fileName1 = "aaa.jpg";
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/x-download");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName1);
            ServletOutputStream out = response.getOutputStream();
            byte[] content = new byte[1024];
            int length = -1;
            while ((length = bais.read(content)) != -1) {
                out.write(content, 0, length);
                out.flush();
            }
            out.close();
            bais.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 文件下载方式二:Controller直接返回这个ResponseEntity<byte[]>
     * @return
     */
    public ResponseEntity<byte[]> download2() {
        byte[] content = fastFileStorageClient.downloadFile("group1", "M00/83/F7/wKiNgVplw4GAKqNnAANbI4wCqFY733.jpg", new DownloadByteArray());
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment",  "aaa.jpg");
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(content, headers, HttpStatus.CREATED);
    }
}
除了FastDFSClientWrapper类中用到的api,客户端提供的api还有很多,可根据自身的业务需求,将其它接口也添加到工具类中即可。如下所示:

// 上传文件,并添加文件元数据
StorePath uploadFile(InputStream inputStream, long fileSize, String fileExtName, Set<MateData> metaDataSet);
// 获取文件元数据
Set<MateData> getMetadata(String groupName, String path);
// 上传图片并同时生成一个缩略图
StorePath uploadImageAndCrtThumbImage(InputStream inputStream, long fileSize, String fileExtName,
            Set<MateData> metaDataSet);
// 。。。
在项目中使用FastDFSClientWrapper:

@Controller
public class MyController {

    @Autowired
    private FastDFSClientWrapper dfsClient;

    // 上传图片
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String upload(MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 省略业务逻辑代码。。。
        String imgUrl = dfsClient.uploadFile(file);
        // 。。。。
        return xxxx;

    }
}






FastDFS是一个开源的轻量级分布式文件系统,它提供了高性能的文件存储和访问服务。Spring Boot是一个用于构建独立的、生产级别的Spring应用程序的框架。将FastDFS集成到Spring Boot中可以实现在Spring应用程序中使用FastDFS提供的文件存储和访问服务。 要实现FastDFS集成Spring Boot,你可以按照以下步骤进行操作: 1. 引入FastDFS的依赖:在Spring Boot项目的pom.xml文件中,添加FastDFS的依赖。你可以在Maven中央仓库中找到FastDFS的相关依赖。 2. 配置FastDFS的连接信息:在Spring Boot的配置文件(application.properties或application.yml)中,配置FastDFS的连接信息,如Tracker服务器的地址、端口号等。 3. 编写FastDFS的客户端:在Spring Boot应用程序中编写FastDFS客户端的代码,用于连接FastDFS服务器,并实现文件的上传、下载、删除等操作。 4. 集成Swagger:如果你想方便地测试和使用FastDFS的功能,你可以集成Swagger,它提供了一个用户友好的API文档和测试界面。 通过以上步骤,你就可以实现FastDFS集成到Spring Boot中,从而在Spring Boot应用程序中使用FastDFS的文件存储和访问服务。<span class="em">1</span> #### 引用[.reference_title] - *1* [FastDFS源码封装(SpringBoot集成FastDFS)](https://download.youkuaiyun.com/download/fjxcsdn/12051041)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值