springboot整合FastDFS

一、前言

《FastDFS安装与nginx整合》介绍了FastDFS的安装与基本使用,本节我们重点介绍下在springboot项目中,如何使用FastDFS。

二、项目搭建

2.1 创建项目

创建一个springboot项目,我们将引入thymeleaf作为前端测试,pom文件具体如下:

xml 复制代码
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.11.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.github.tobato/fastdfs-client -->
        <dependency>
            <groupId>com.github.tobato</groupId>
            <artifactId>fastdfs-client</artifactId>
            <version>1.27.2</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

2.2 配置application.yml

yaml 复制代码
fdfs:
  so-timeout: 1500
  connect-timeout: 600
  thumb-image:
    height: 300
    width: 300
  web-server-url: 192.168.33.10:10005/  #nginx代理访问路径
  tracker-list:
    - 192.168.33.10:22122

2.3 加载FastDFS配置类

ComponetImport.java

java 复制代码
@Configuration
@Import(FdfsClientConfig.class)
// 解决jmx重复注册bean的问题
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
public class ComponetImport {
}

2.4 FastDFS工具类

FastDFSClient.java

java 复制代码
@Component
@Slf4j
public class FastDFSClient {

    @Autowired
    private FastFileStorageClient storageClient;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    /**
     * 上传文件
     * @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 file 文件对象
     * @return 文件访问地址
     * @throws IOException
     */
    public String uploadFile(File file) throws IOException {
        FileInputStream inputStream = new FileInputStream (file);
        StorePath storePath = storageClient.uploadFile(inputStream,file.length(), FilenameUtils.getExtension(file.getName()),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 = fdfsWebServer.getWebServerUrl() + storePath.getFullPath();
        return fileUrl;
    }

    /**
     * 下载文件
     * @param fileUrl 文件url
     * @return
     */
    public byte[]  download(String fileUrl) {
        String group = fileUrl.substring(0, fileUrl.indexOf("/"));
        String path = fileUrl.substring(fileUrl.indexOf("/") + 1);
        byte[] bytes = storageClient.downloadFile(group, path, new DownloadByteArray());
        return bytes;
    }

    /**
     * 删除文件
     * @param fileUrl 文件访问地址
     * @return
     */
    public void deleteFile(String fileUrl) {
        if (StringUtils.isEmpty(fileUrl)) {
            return;
        }
        try {
            String group = fileUrl.substring(0, fileUrl.indexOf("/"));
            String path = fileUrl.substring(fileUrl.indexOf("/") + 1);
            storageClient.deleteFile(group, path);
        } catch (FdfsUnsupportStorePathException e) {
            log.warn(e.getMessage());
        }
    }
    
}

三、测试

3.1 编写测试类

FastDFSController.java

java 复制代码
@RestController
@RequestMapping("/fdfs")
public class FastDFSController {

    @Autowired
    private FastDFSClient fdfsClient;

    /**
     * 文件上传
     * @param file
     * @return
     * @throws Exception
     */
    @RequestMapping("/upload")
    public Map<String,Object> upload(MultipartFile file) throws Exception{
        String url = fdfsClient.uploadFile(file);
        Map<String,Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("msg", "上传成功");
        result.put("url", url);
        return result;
    }

    /**
     * 文件下载
     * @param fileUrl  url 开头从组名开始
     * @param response
     * @throws Exception
     */
    @RequestMapping("/download")
    public void  download(String fileUrl, HttpServletResponse response) throws Exception{
        byte[] data = fdfsClient.download(fileUrl);
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("test.jpg", "UTF-8"));

        // 写出
        ServletOutputStream outputStream = response.getOutputStream();
        IOUtils.write(data, outputStream);
    }

    /**
     * 删除下载
     * @param fileUrl  url 开头从组名开始
     * @throws Exception
     */
    @RequestMapping("/delete")
    public Map<String,Object>  delete(String fileUrl) throws Exception{
        fdfsClient.deleteFile(fileUrl);
        Map<String,Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("msg", "删除成功");
        return result;
    }
}

3.2 测试页面

templates\index.html

html 复制代码
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>文件上传</title>
    <style>
        form {
            margin-top: 30px;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-md-4 col-sm-4"></div>
        <div class="col-md-4 col-sm-4">
            <h2> FastDFS 文件上传</h2>
            <form th:action="@{/fdfs/upload}" method="post" enctype="multipart/form-data">
                <div class="form-group">
                    <input type="file" name="file" id="exampleInputFile">
                </div>
                <button type="submit" class="btn btn-default">上传</button>
            </form>
        </div>
        <div class="col-md-4 col-sm-4"></div>
    </div>
</div>
</body>
</html>

3.3 测试

文件上传与浏览测试

浏览器访问http://127.0.0.1:8080/

文件删除测试

http://127.0.0.1:8080/fdfs/delete?fileUrl=group1/M00/00/00/wKghCmMUpV2AVmsxAABD4k7DNRw753.jpg

再次访问图片

更多参考:

FastDFS_Client

FastDFS论坛

FastDFS常见问题

相关推荐
H H.9 分钟前
Java企业级开发:从框架到工程化实战
java·开发语言·经验分享·其他·课程设计
顧棟1 小时前
组件生命周期设计:从硬编码初始化到状态机
java·ide
程序猿DD7 小时前
OctaFuse 2.20.0:MCP 用业务账号直接登录授权,请求日志合并工具调用
后端
特立独行的猫A9 小时前
别再用 nohup 了:让应用在后台常驻的正确姿势与 systemd 服务详解
java·后端·python
一起_java9 小时前
技术文章-基于Dify-Agent的智能问答系统设计与实现
java·spring boot·后端·agent·dify
码事漫谈10 小时前
2027年火的很可能是AI工作台
后端
Flynn Liang10 小时前
I/O 密集型高并发实战:Java 服务 10 维优化,从线程打满到 10 万 QPS
java·spring boot·性能优化·高并发·系统设计·虚拟线程·io密集型
吃我一窝jio11 小时前
Python与Go线程模型深度对比
java·开发语言·python
这个昵称不容易12 小时前
SpringBoot 购物推荐网站的设计与实现:120 个 Java 文件、147 个接口、13 张表,附真实运行截图
java·springboot·毕设