首页 > 其他分享 >Spring Boot 3.x集成FastDFS记录

Spring Boot 3.x集成FastDFS记录

时间:2024-06-04 14:29:00浏览次数:12  
标签:String Spring org storePath Boot file import FastDFS path

最近在做一个课程,需要用讲一下SpringBoot 使用文件上传的功能,选择了FastDFS作为文件存储OSS。Spring Boot是最新的3.3.0版本,JDK版本是17,中间有一些坑,下面记录一下。

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>3.3.0</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
    <java.version>17</java.version>
</properties>

一,安装FastDFS

FastDFS高可用集群架构配置搭建及使用_fdfs 集群 使用-CSDN博客

二,集成

1,引入pom

<!-- FastDFS Start 如果已经引入了log4j的实现,需要排除掉fastdfs的-->
<dependency>
    <groupId>com.github.tobato</groupId>
    <artifactId>fastdfs-client</artifactId>
    <version>1.27.2</version>
    <exclusions>
       <exclusion>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-api</artifactId>
       </exclusion>
       <exclusion>
          <groupId>org.slf4j</groupId>
          <artifactId>jcl-over-slf4j</artifactId>
       </exclusion>
       <exclusion>
          <groupId>ch.qos.logback</groupId>
          <artifactId>logback-classic</artifactId>
       </exclusion>
       <exclusion>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-logging</artifactId>
       </exclusion>
    </exclusions>
</dependency>
<!-- 注解@PostConstruct包路径在jdk17是无效的, 需要补充下面的依赖 -->
<dependency>
    <groupId>javax.annotation</groupId>
    <artifactId>javax.annotation-api</artifactId>
    <version>1.3.2</version>
</dependency>
<!-- FastDFS End -->

2,导入FastDFS配置

fdfs:
  open: true
  so-timeout: 1501
  connect-timeout: 601
  thumb-image: #缩略图生成参数
    width: 150
    height: 150
  tracker-list: #TrackerList参数,支持多个
    - 10.250.112.141:22122
file:
  domain: http://10.250.112.143:8888/

3,工具类

(1)FastDFSClient
import com.github.tobato.fastdfs.domain.fdfs.MetaData;
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 jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashSet;
import java.util.Set;

@Component
public class FastDFSClient {
    @Resource
    private FastFileStorageClient fastFileStorageClient;

    /**
     * 上传
     *
     * @param file
     * @return
     * @throws IOException
     */
    public StorePath upload(MultipartFile file) throws IOException {
        // 设置文件信息
        Set<MetaData> mataData = new HashSet<>();
        mataData.add(new MetaData("author", "fastdfs"));
        mataData.add(new MetaData("description", file.getOriginalFilename()));
        // 上传
        StorePath storePath = fastFileStorageClient.uploadFile(
            file.getInputStream(), file.getSize(),
            FilenameUtils.getExtension(file.getOriginalFilename()),
            null);
        return storePath;
    }

    /**
     * 上传文件
     *
     * @param file
     * @return
     * @throws FileNotFoundException
     */
    public String uploadFile(String file) throws FileNotFoundException {
        File file1 = new File(file);
        if (!file1.exists()) {
            return null;
        }

        FileInputStream fileInputStream = new FileInputStream(file1);
        // 上传文件和Metadata
        StorePath path = fastFileStorageClient.uploadFile(fileInputStream, file1.length(), FilenameUtils.getExtension(file1.getName()),
            null);
        return path.getFullPath();
    }

    /**
     * 上传文件
     *
     * @param file
     * @return
     * @throws IOException
     */
    public String uploadFile(File file) throws IOException {
        if (file == null) {
            return null;
        }

        FileInputStream fileInputStream = new FileInputStream(file);
        // 上传文件和Metadata
        StorePath path = fastFileStorageClient.uploadFile(fileInputStream, file.length(), FilenameUtils.getExtension(file.getName()),
            null);
        fileInputStream.close();
        return path.getFullPath();
    }

    /**
     * 删除
     *
     * @param path
     */
    public void delete(String path) {
        fastFileStorageClient.deleteFile(path);
    }

    /**
     * 删除
     *
     * @param group
     * @param path
     */
    public void delete(String group, String path) {
        fastFileStorageClient.deleteFile(group, path);
    }

    /**
     * 文件下载
     *
     * @param path     文件路径,例如:/group1/path=M00/00/00/itstyle.png
     * @param filename 下载的文件命名
     * @return
     */
    public void download(String path, String filename, HttpServletResponse response) throws IOException {
        // 获取文件
        StorePath storePath = StorePath.parseFromUrl(path);
        if (StringUtils.isBlank(filename)) {
            filename = FilenameUtils.getName(storePath.getPath());
        }
        byte[] bytes = fastFileStorageClient.downloadFile(storePath.getGroup(), storePath.getPath(), new DownloadByteArray());
        response.reset();
        response.setContentType("applicatoin/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
        ServletOutputStream out = response.getOutputStream();
        out.write(bytes);
        out.close();
    }
}
(2)FastDFSConfig
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;

@Configuration
@Import(FdfsClientConfig.class)
// 解决jmx重复注册bean的问题
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
public class FastDFSConfig {
}
(3)FastDfsStorePath
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import lombok.Data;

@Data
public class FastDfsStorePath {
    private String group;
    private String path;
    private String fullPath;
    private String fileUrl;

    public FastDfsStorePath(StorePath storePath) {
        this.group = storePath.getGroup();
        this.path = storePath.getPath();
        this.fullPath = storePath.getFullPath();
    }
}

4,上传文件接口

@Value("${file.domain}")
private String fileDomain;
@Operation(summary = "上传文件")
@PostMapping("/file")
@ResponseBody
public RestResponse<FastDfsStorePath> updateFile(@RequestParam("file") MultipartFile file) throws IOException {
    log.info("=====>文件名: {}", file.getOriginalFilename());
    StorePath storePath = fastDFSClient.upload(file);
    FastDfsStorePath fastDfsStorePath = new FastDfsStorePath(storePath);
    fastDfsStorePath.setFileUrl(fileDomain + storePath.getFullPath());
    return RestResponse.success(fastDfsStorePath);
}

接口返回

{

    "code": 200,

    "message": null,

    "data": {

        "group": "group1",

        "path": "M00/00/01/CpaE3mZer6WANEKKADTPweiDcA8273.png",

        "fullPath": "group1/M00/00/01/CpaE3mZer6WANEKKADTPweiDcA8273.png",

        "fileUrl": "http://10.250.112.143:8888/group1/M00/00/01/CpaE3mZer6WANEKKADTPweiDcA8273.png"

    },

    "requestId": null,

    "success": true

}

完毕!

标签:String,Spring,org,storePath,Boot,file,import,FastDFS,path
From: https://blog.csdn.net/wangerrong/article/details/139441224

相关文章

  • 基于SpringCloudAlibaba+Sharding-JDBC的微服务的分库分表设计
    胡弦,视频号2023年度优秀创作者,互联网大厂P8技术专家,SpringCloudAlibaba微服务架构实战派(上下册)和RocketMQ消息中间件实战派(上下册)的作者,资深架构师,技术负责人,极客时间训练营讲师,四维口袋KVP最具价值技术专家,技术领域专家团成员,2021电子工业出版社年度优秀作者,获得2023电......
  • 基于SpringBoot的英语单词小程序的设计与实现(期末大作业)+附源码+数据库
    摘要随着经济的不断发展与进步,语言的全球化慢慢的变成现今世纪非常重要的一种发展趋势。本文针对大学生在校阶段开发了一个基于SpringBoot的英语等级助考系统,通过线上小程序学习的方式,减少学生学习时间、降低学生学习压力、增强学习效果。该系统采用微信开发工具和基于SpringB......
  • Springboot计算机毕业设计医院门诊小程序【附源码】开题+论文+mysql+程序+部署
    本系统(程序+源码)带文档lw万字以上 文末可获取一份本项目的java源码和数据库参考。系统程序文件列表开题报告内容研究背景随着移动互联网技术的迅猛发展,人们对于医疗服务的便捷性和高效性提出了更高要求。传统医院门诊流程复杂、耗时较长,已无法满足现代患者快速就医的需求......
  • Springboot计算机毕业设计医院排班&预约小程序【附源码】开题+论文+mysql+程序+部署
    本系统(程序+源码)带文档lw万字以上 文末可获取一份本项目的java源码和数据库参考。系统程序文件列表开题报告内容研究背景在现代医疗服务体系中,医生与患者的对接效率直接影响着医院的运营效率和患者的就医体验。传统的排班与预约方式往往存在信息更新不及时、预约流程繁琐......
  • JAVA计算机毕业设计基于Web的小学学科数字教学资源管理系统的开发与设计(附源码+spring
    本系统(程序+源码)带文档lw万字以上 文末可获取一份本项目的java源码和数据库参考。系统程序文件列表开题报告内容研究背景在信息化时代的浪潮下,教育领域正经历着深刻的变革。随着互联网技术的飞速发展,数字教学资源已成为小学学科教育中不可或缺的一部分。然而,当前许多小学......
  • JAVA计算机毕业设计基于web的校园互助系统设计(附源码+springboot+开题+论文)
    本系统(程序+源码)带文档lw万字以上 文末可获取一份本项目的java源码和数据库参考。系统程序文件列表开题报告内容研究背景随着互联网技术的迅猛发展和普及,校园生活也逐渐步入了数字化、网络化的新阶段。在这样的背景下,校园内的信息交流和互助需求日益增长。然而,传统的校园......
  • Bootstrap框架
    原文链接:https://blog.csdn.net/2301_80068547/article/details/134619359一、Bootstrap简介Bootstrap来自Twitter(推特),是目前最受欢迎的前端框架。Bootstrap是基于HTML、CSS和JavaScript的,它简洁灵活,使得Web开发更加快捷。中文官网:https://www.bootcss.com/官网:http......
  • Spring boot - 仅当 JavaMailSender 豆存在时自动配置
    我相信这应该很简单,但我想不通。我有一个这样的配置类:@Configuration@AutoConfigureAfter(MailSenderAutoConfiguration.class)公共类MyMailConfiguration{@Bean@ConditionalOnBean(JavaMailSender.class)publicMyMailermyMailer(JavaMailSender......
  • OpenTelemetry agent 对 Spring Boot 应用的影响:一次 SPI 失效的案例
    背景前段时间公司领导让我排查一个关于在JDK21环境中使用SpringBoot配合一个JDK18新增的一个SPI(java.net.spi.InetAddressResolverProvider)不生效的问题。但这个不生效的前置条件有点多:JDK的版本得在18+SpringBoot3.x还在额外再配合使用-javaagent:openteleme......
  • spring boot工具类
    正文:断言断言是一个逻辑判断,用于检查不应该发生的情况Assert关键字在JDK1.4中引入,可通过JVM参数-enableassertions开启SpringBoot中提供了Assert断言工具类,通常用于数据合法性检查//要求参数object必须为非空(NotNull),否则抛出异常,不予放行//参数message参数用......