SpringBoot2.0整合Fastdfs 示例

本文介绍如何在Spring Boot项目中集成FastDFS,并提供文件上传、下载及删除等基本操作的实现示例。

1.简介

       自己在网上看了很多资料,写的花里胡巧的,到处是工具类,其实就几行代码。

       网上有两种连接fastdfs的pom依赖,1:fastdfs-client,2:fastdfs-client-java,第二种看到别人的实例,太花了,不易读,这里使用的是第一种方式

       还有的坑就是,好多人的用的都是springboot1.5版本,在pom引入fastdfs依赖(1.25.x)是有冲突的,最后在网上找到了原作者的git账号,原作者的版本已经更新到1.26.2了,这里用的是最新的

       这里把fastdfs的一些简单操作代码分享下。

       

2.引入FastDfs依赖

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

3.application.yml配置文件

# ===================================================================
# 分布式文件系统FDFS配置
# ===================================================================
fdfs:
  so-timeout: 1501
  connect-timeout: 2000
  thumb-image:             #缩略图生成参数
    width: 150
    height: 150
  tracker-list:            #TrackerList参数,支持多个
    - 127.0.0.1:22122

 4.controller 接口编写

package com.springbootfastdfs.controller;

import com.github.tobato.fastdfs.domain.MataData;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.sun.deploy.net.URLEncoder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

@RestController
@Api(description = "fastdfs接口API")
public class TestApi {

    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    /**
     * 文件上传
     *
     * @param file
     * @return
     * @throws IOException
     */
    @ApiOperation("文件上传")
    @PostMapping("/uppload")
    public StorePath test(@RequestParam MultipartFile file) throws IOException {

        // 设置文件信息
        Set<MataData> mataData = new HashSet<>();
        mataData.add(new MataData("author", "zonghui"));
        mataData.add(new MataData("description", "xxx文件,嘿嘿嘿"));

        // 上传   (文件上传可不填文件信息,填入null即可)
        StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()), mataData);

        return storePath;
    }

    /**
     * 文件删除
     *
     * @param path
     * @return
     */
    @ApiOperation("文件删除")
    @DeleteMapping("/delete")
    public String delete(@RequestParam String path) {

        // 第一种删除:参数:完整地址
        fastFileStorageClient.deleteFile(path);

        // 第二种删除:参数:组名加文件路径
        // fastFileStorageClient.deleteFile(group,path);

        return "恭喜恭喜,删除成功!";
    }


    /**
     * 文件下载
     *
     * @param path
     * @return
     */
    @ApiOperation("文件下载")
    @GetMapping("/download")
    public void downLoad(@RequestParam String group, @RequestParam String path, @RequestParam String fileName, HttpServletResponse response) throws IOException {

        // 获取文件
        byte[] bytes = fastFileStorageClient.downloadFile(group, path, new DownloadByteArray());

        //设置相应类型application/octet-stream        (注:applicatoin/octet-stream 为通用,一些其它的类型苹果浏览器下载内容可能为空)
        response.reset();
        response.setContentType("applicatoin/octet-stream");
        //设置头信息                 Content-Disposition为属性名  附件形式打开下载文件   指定名称  为 设定的fileName
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        // 写入到流
        ServletOutputStream out = response.getOutputStream();
        out.write(bytes);
        out.close();
    }

}
### 整合 FastDFSSpring Boot 3 的方法 为了在 Spring Boot 3 中集成 FastDFS,可以按照以下方式实现完整的功能支持。以下是详细的说明: #### 1. 添加依赖项 首先,在 `pom.xml` 文件中引入必要的依赖项来支持 FastDFSSpring Boot 的整合。 ```xml <dependencies> <!-- Spring Boot Starter Web --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- FastDFS Client Java SDK --> <dependency> <groupId>io.github.yedaxia</groupId> <artifactId>fastdfs-client-java</artifactId> <version>1.29.1</version> </dependency> </dependencies> ``` 以上配置提供了基础的 Web 支持以及 FastDFS 客户端的支持[^4]。 --- #### 2. 配置 FastDFS 参数 创建一个名为 `application.yml` 或 `application.properties` 的文件,并添加如下配置以连接到 FastDFS 服务。 对于 YAML 格式的配置: ```yaml fdfs: so-timeout: 15000 connect-timeout: 5000 tracker-list: - 192.168.1.100:22122 - 192.168.1.101:22122 ``` 或者使用 Properties 格式: ```properties fdfs.so-timeout=15000 fdfs.connect-timeout=5000 fdfs.tracker-list=192.168.1.100:22122,192.168.1.101:22122 ``` 这些参数定义了客户端与 Tracker Server 进行通信的时间设置和地址列表[^5]。 --- #### 3. 创建 FastDFS 工具类 编写一个工具类用于封装上传、下载和其他操作逻辑。 ```java import org.csource.common.NameValuePair; import org.csource.fastdfs.*; import java.io.IOException; public class FastDFSTool { static { try { String path = Thread.currentThread().getContextClassLoader() .getResource("tracker.conf").getPath(); ClientGlobal.init(path); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e.getCause()); } } public static String uploadFile(String localFilePath, String fileExtName) throws IOException, MyException { TrackerClient tracker = new TrackerClient(); TrackerServer trackerServer = tracker.getConnection(); StorageServer storageServer = null; StorageClient1 storageClient1 = new StorageClient1(trackerServer, storageServer); NameValuePair[] metaList = new NameValuePair[]{new NameValuePair("author", "SpringBoot")}; String remoteFileName = storageClient1.upload_file1(localFilePath, fileExtName, metaList); if (remoteFileName != null && !"".equals(remoteFileName)) { return remoteFileName; } else { throw new RuntimeException("Upload failed"); } } } ``` 此代码片段展示了如何初始化 FastDFS 并执行文件上传的操作[^6]。 --- #### 4. 编写 Controller 层接口 通过 RESTful API 提供对外的服务调用入口。 ```java @RestController @RequestMapping("/file") public class FileController { @PostMapping("/upload") public ResponseEntity<String> upload(@RequestParam("file") MultipartFile multipartFile) throws Exception { if (!multipartFile.isEmpty()) { String originalFilename = multipartFile.getOriginalFilename(); int index = originalFilename.lastIndexOf("."); String extName = originalFilename.substring(index + 1).toLowerCase(); String filePath = multipartFile.getResource().getFile().getAbsolutePath(); String resultPath = FastDFSTool.uploadFile(filePath, extName); return ResponseEntity.ok(resultPath); } else { return ResponseEntity.badRequest().body("Empty file is not allowed."); } } } ``` 这段代码实现了接收前端传来的文件并将其存储至 FastDFS 系统中的功能[^7]。 --- #### 5. 测试验证 启动应用程序后,可以通过 Postman 或其他测试工具发送请求来进行实际的功能检验。 例如,向 `/file/upload` 接口发起 POST 请求时附带要上传的文件即可完成测试过程。 --- ### 总结 上述步骤涵盖了从环境搭建到具体编码实践的过程,能够帮助开发者快速掌握如何将 FastDFS 成功嵌入基于 Spring Boot 3 构建的应用程序之中[^8]。
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值