首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >springboot集成fastdfs使用com.github.tobato的fastdfs-client内附Demo下载(2021-06-18)

springboot集成fastdfs使用com.github.tobato的fastdfs-client内附Demo下载(2021-06-18)

作者头像
知识浅谈
修改2022-05-16 22:31:57
修改2022-05-16 22:31:57
1.3K00
代码可运行
举报
文章被收录于专栏:分享学习分享学习
运行总次数:0
代码可运行

Demo下载:公众号:知识浅谈 后台回复 fastdfsdemo 获取下载地址

具体服用过程如下,服用之前确保fdfs_trackerd fdfs_storaged nginx 配置好并且已经运行

代码语言:javascript
代码运行次数:0
运行
复制
[root@iZhp333b21cruky4l17cm0Z /]# service fdfs_trackerd status
● fdfs_trackerd.service - LSB: FastDFS tracker server
   Loaded: loaded (/etc/rc.d/init.d/fdfs_trackerd; bad; vendor preset: disabled)
   Active: active (running) since Thu 2021-06-17 20:08:51 CST; 14h ago
     Docs: man:systemd-sysv-generator(8)
[root@iZhp333b21cruky4l17cm0Z /]# service fdfs_storaged status
● fdfs_storaged.service - LSB: FastDFS storage server
   Loaded: loaded (/etc/rc.d/init.d/fdfs_storaged; bad; vendor preset: disabled)
   Active: active (running) since Fri 2021-06-18 09:12:46 CST; 1h 21min ago
     Docs: man:systemd-sysv-generator(8)
[root@iZhp333b21cruky4l17cm0Z /]# service nginx status
Redirecting to /bin/systemctl status nginx.service
● nginx.service - nginx - high performance web server
   Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled)
   Active: active (running) since Wed 2021-06-16 16:03:19 CST; 1 day 18h ago
     Docs: http://nginx.org/en/docs/

创建springboot项目

具体的创建流程就不列出来了,

引入依赖

代码语言:javascript
代码运行次数:0
运行
复制
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.englishcode</groupId>
    <artifactId>fastdfsdemo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>fastdfsdemo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <!--fastdfs依赖-->
        <!-- 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>



        <!--thymeleaf依赖-->
        <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>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

修改配置文件

代码语言:javascript
代码运行次数:0
运行
复制
#fastdfs 配置
fdfs:
  # 读取时间
  so-timeout: 1500
  # 连接超时时间
  connect-timeout: 600
  # 缩略图
  thumb-image:
    width: 150
    height: 150
  # Tracker服务,确保tracker storage nginx已经启动
  tracker-list:
    - 39.104.67.142:22122

创建配置类

代码语言:javascript
代码运行次数:0
运行
复制
package com.englishcode.fastdfsdemo.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;

/**
 * @author: YinLei
 * Package:  com.englishcode.fastdfsdemo.config
 * @date: 2021/6/18 10:02
 * @Description: fastdfs配置类
 * @version: 1.0
 */
@Configuration
@Import(FdfsClientConfig.class)
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
public class FdfsConfig {

}

创建工具类

代码语言:javascript
代码运行次数:0
运行
复制
package com.englishcode.fastdfsdemo.utils;

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 org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Set;

/**
 * @author: YinLei
 * Package:  com.englishcode.fastdfsdemo.utils
 * @date: 2021/6/18 10:03
 * @Description: Fastdfs客户端工具类
 * @version: 1.0
 */
@Component
public class FdfsClientWrapper {

    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    public String uploadFile(MultipartFile file) throws IOException {
        if (file != null) {
            byte[] bytes = file.getBytes();
            long fileSize = file.getSize();
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            return this.uploadFile(bytes, fileSize, extension);
        }
        return null;
    }

    /**
     * 文件上传
     *
     * @param bytes     文件字节
     * @param fileSize  文件大小
     * @param extension 文件扩展名
     * @return 返回文件路径(卷名和文件名)
     */
    public String uploadFile(byte[] bytes, long fileSize, String extension) {
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        // 元数据
        Set<MetaData> metaDataSet = new HashSet<MetaData>();
        metaDataSet.add(new MetaData("dateTime", LocalDateTime.now().toString()));
        metaDataSet.add(new MetaData("Author","Layne"));
        StorePath storePath = fastFileStorageClient.uploadFile(bais, fileSize, extension, metaDataSet);
        return storePath.getFullPath();
    }

    /**
     * 下载文件
     *
     * @param filePath 文件路径
     * @return 文件字节
     * @throws IOException
     */
    public byte[] downloadFile(String filePath) throws IOException {
        byte[] bytes = null;
        if (StringUtils.isNotBlank(filePath)) {
            String group = filePath.substring(0, filePath.indexOf("/"));
            String path = filePath.substring(filePath.indexOf("/") + 1);
            DownloadByteArray byteArray = new DownloadByteArray();
            bytes = fastFileStorageClient.downloadFile(group, path, byteArray);
        }
        return bytes;
    }

    /**
     * 删除文件
     *
     * @param filePath 文件路径
     */
    public void deleteFile(String filePath) {
        if (StringUtils.isNotBlank(filePath)) {
            fastFileStorageClient.deleteFile(filePath);
        }
    }

}

创建form文件上传表单{/resource/template下}

代码语言:javascript
代码运行次数:0
运行
复制
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>上传文件</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
    选择文件:<input type="file" name="file"><br />
    <input type="submit" value="提交">
</form>
</body>
</html>

创建测试controller

代码语言:javascript
代码运行次数:0
运行
复制
package com.englishcode.fastdfsdemo.controller;

import com.englishcode.fastdfsdemo.utils.FdfsClientWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @author: YinLei
 * Package:  com.englishcode.fastdfsdemo.controller
 * @date: 2021/6/18 10:07
 * @Description: 文件上传下在删除测试Controller
 * @version: 1.0
 */
@Controller
public class FileUploadController {

    private static Logger log = LoggerFactory.getLogger(FileUploadController.class);

    @Autowired
    private FdfsClientWrapper fdfsClientWrapper;

    /**
     * 进入上传页面
     *
     * @return 路径
     */
    @RequestMapping(value = "/")
    public String form() {
        return "form";
    }

    /**
     * 上传文件
     *
     * @param file 文件
     * @return 文件路径
     */
    @RequestMapping(value = "upload")
    @ResponseBody
    public String uploadFile(MultipartFile file) {
        String filePath = null;
        try {
            filePath = fdfsClientWrapper.uploadFile(file);
        } catch (IOException e) {
            log.error("上传文件异常:{}", e);
            return "上传文件失败";
        }
        return filePath;
    }

    /**
     * 下载文件
     *
     * @param filePath 文件路径
     * @return
     */
    @RequestMapping(value = "download")
    public void downloadFile(String filePath, HttpServletResponse response) {
        ServletOutputStream outputStream = null;
        try {
            byte[] bytes = fdfsClientWrapper.downloadFile(filePath);
            String fileName = "fdfs.jpg";
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            response.setCharacterEncoding("UTF-8");
            if (bytes != null) {
                outputStream = response.getOutputStream();
                outputStream.write(bytes);
                outputStream.flush();
            }
        } catch (IOException e) {
            log.debug("下载文件输出流异常:{}", e);
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                log.debug("下载文件关闭流异常:{}", e);
            }
        }
    }

    /**
     * 删除文件
     *
     * @param filePath 文件路径
     * @return 删除结果
     */
    @RequestMapping(value = "delete")
    @ResponseBody
    public String deleteFile(String filePath) {
        fdfsClientWrapper.deleteFile(filePath);
        return "删除成功";
    }

}

测试

  • 文件上传   浏览器访问:http://localhost:8080/,选择一种图片,点击提交,记录返回的文件路径filrPath(卷名+文件名)。
  • 文件浏览   浏览器访问:http://ip:8888/[filePath] //这个地址是storage所在服务器的ip,filePath为上传之后返回的遗传字符串filePath。
  • 文件下载(下载的文件名为:fdfs.jpg)   浏览器访问:http://localhost:8080/download?filePath=[filePath]
  • 文件删除   浏览器访问:http://localhost:8080/delete?filePath=[filePath]
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021/06/18 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 创建springboot项目
  • 引入依赖
  • 修改配置文件
  • 创建配置类
  • 创建工具类
  • 创建form文件上传表单{/resource/template下}
  • 创建测试controller
  • 测试
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档