1. 简介

  基于tobato的fastdfs-client是一个功能完善的FastDFS客户端工具,它是在FastDFS作者YuQing发布的客户端基础上进行了大量的重构,提供了上传、下载、删除、生成缩略图等API。

2. 安装FastDFS

  Docker部署FastDFS(附示例代码)

3. 示例代码

  • 创建工程

  • 修改pom.xml
<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>
<groupId>com.c3stones</groupId>
<artifactId>spirng-boot-fastdfs-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spirng-boot-fastdfs-demo</name>
<description>Spring Boot FastDFS Demo</description> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.8.RELEASE</version>
<relativePath />
</parent> <dependencies>
<dependency>
<groupId>com.github.tobato</groupId>
<artifactId>fastdfs-client</artifactId>
<version>1.26.6</version>
</dependency>
<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-starter-test</artifactId>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>
  • 创建配置文件application.yml
#fastdfs 配置
fdfs:
# 读取时间
so-timeout: 1500
# 连接超时时间
connect-timeout: 600
# 缩略图
thumb-image:
width: 150
height: 150
# Tracker服务
tracker-list:
- 192.168.0.100:22122
  • 创建配置类
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableMBeanExport;
import org.springframework.context.annotation.Import;
import org.springframework.jmx.support.RegistrationPolicy; import com.github.tobato.fastdfs.FdfsClientConfig; /**
* FastDFS Client配置
*
* @author CL
*
*/
@Configuration
@Import(FdfsClientConfig.class)
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
public class FdfsConfig { }
  • 创建包装类
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Set; 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 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; /**
* FastDFS客户端包装类
*
* @author CL
*
*/
@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()));
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);
}
} }
  • 创建文件上传Controller
import java.io.IOException;
import java.net.URLEncoder; import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse; 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 com.c3stones.wapper.FdfsClientWrapper; /**
* 文件上传Controller
*
* @author CL
*
*/
@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 "删除成功";
} }
  • 创建启动类
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; /**
* 启动类
*
* @author CL
*
*/
@SpringBootApplication
public class Application { public static void main(String[] args) {
SpringApplication.run(Application.class, args);
} }
  • 在resource下创建templates/form.html
<!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>
  • 启动项目

4. 测试

5. 项目地址

  spirng-boot-fastdfs-demo

SpringBoot集成基于tobato的fastdfs-client实现文件上传下载和删除的更多相关文章

  1. Java 客户端操作 FastDFS 实现文件上传下载替换删除

    FastDFS 的作者余庆先生已经为我们开发好了 Java 对应的 SDK.这里需要解释一下:作者余庆并没有及时更新最新的 Java SDK 至 Maven 中央仓库,目前中央仓库最新版仍旧是 1.2 ...

  2. RPC基于http协议通过netty支持文件上传下载

    本人在中间件研发组(主要开发RPC),近期遇到一个需求:RPC基于http协议通过netty支持文件上传下载 经过一系列的资料查找学习,终于实现了该功能 通过netty实现文件上传下载,主要在编解码时 ...

  3. 基于Spring Mvc实现的Excel文件上传下载

    最近工作遇到一个需求,需要下载excel模板,编辑后上传解析存储到数据库.因此为了更好的理解公司框架,我就自己先用spring mvc实现了一个样例. 基础框架 之前曾经介绍过一个最简单的spring ...

  4. SpringBoot入门一:基础知识(环境搭建、注解说明、创建对象方法、注入方式、集成jsp/Thymeleaf、logback日志、全局热部署、文件上传/下载、拦截器、自动配置原理等)

    SpringBoot设计目的是用来简化Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置.通过这种方式,SpringBoot致力于在蓬勃发 ...

  5. 一、手把手教你docker搭建fastDFS文件上传下载服务器

    在搭建fastDFS文件上传下载服务器之前,你需要准备的有一个可连接的linux服务器,并且该linux服务器上已经安装了docker,若还有没安装docker的,先百度自行安装docker. 1.执 ...

  6. vue+Ueditor集成 [前后端分离项目][图片、文件上传][富文本编辑]

    后端DEMO:https://github.com/coderliguoqing/UeditorSpringboot 前端DEMO:https://github.com/coderliguoqing/ ...

  7. 艺萌文件上传下载及自动更新系统(基于networkComms开源TCP通信框架)

    1.艺萌文件上传下载及自动更新系统,基于Winform技术,采用CS架构,开发工具为vs2010,.net2.0版本(可以很容易升级为3.5和4.0版本)开发语言c#. 本系统主要帮助客户学习基于TC ...

  8. FastDFS实现文件上传下载实战

    正好,淘淘商城讲这一块的时候,我又想起来当时老徐让我写过一个关于实现FastDFS实现文件上传下载的使用文档,当时结合我们的ITOO的视频系统和毕业论文系统,整理了一下,有根据网上查到的知识,总结了一 ...

  9. 转:【专题十一】实现一个基于FTP协议的程序——文件上传下载器

    引言: 在这个专题将为大家揭开下FTP这个协议的面纱,其实学习知识和生活中的例子都是很相通的,就拿这个专题来说,要了解FTP协议然后根据FTP协议实现一个文件下载器,就和和追MM是差不多的过程的,相信 ...

随机推荐

  1. spring cloud gateway 启动报错,Failed to bind on [0.0.0.0:xxx] bind(..) failed: 权限不够

    最近把操作系统迁移到了deepin,不得不说Linux中需要学习的还是有很多的,本地启动网关的时候就遇到一个坑,特此记录一下,报错信息. Caused by: reactor.netty.Channe ...

  2. invalid PID number "" in "/usr/local/nginx/logs/nginx.pid"

    解决办法: $ sudo nginx -c /usr/local/etc/nginx/nginx.conf $ sudo nginx -s reload

  3. Linux学习 - 02 使用 - Centos8 - 『更换rpm/epel包源为国内源』

    1. Centos8 - 『更换rpm/epel包源为国内源』 centos 8 默认是会读取centos.org的mirrorlist的,所以一般来说是不需要配置镜像的. 如果你的网络访问mirro ...

  4. level2行情是什么意思?

    level2行情是由上海证券交易所推出的实时行情信息收费服务产品,主要提供在上海证券交易所上市交易的证券产品的实时交易数据,包括十档行情,买卖队列,逐笔成交,委托总量和加权价格等数据. 投资者根据其功 ...

  5. ABBYY FineReader添加盖章戳记

    PDF编辑器允许您如同在纸质文档上盖章一样在 PDF 文档上添加戳记.您可以从可用的戳记列表中选择戳记或者创建自己的戳记,然后添加任何所需的文本.戳记日期和时间或者图像. 如果要在页面上加上戳记,可以 ...

  6. 如何用FL Studio做电音

    电音制作,自然少不了适合做电音的软件,市面上可以进行电音制作的软件不少,可是如果在这些软件中只能选择一款的话,想必多数人会把票投给FL Studio,毕竟高效率是永远不变的真理,今天就让我们来看看如何 ...

  7. 怎么用导图软件iMindMap整理C语言知识点

    C语言是一门非常基础的编程语言,学习它的难点不在于语言的理解,而在于繁琐的记忆点,而当我们使用思维导图将细碎的知识点拉到框架中去后,C语言的难度就大大降低了. 接下来就为大家介绍一下我使用iMindM ...

  8. guitar pro系列教程(二):Guitar Pro主界面之记谱功能的详细解析【下】

    本章节我们接着上一章节继续讲解关于guitar pro主界面的记谱功能里的符号功能.有兴趣的朋友可以进来一起学习哦. 首先我们看下图,这是点击按钮便会弹出的一个窗口,进入这个窗口,我们会看到" ...

  9. 三. Vue组件化

    1. 认识组件化 1.1 什么是组件化 人面对复杂问题的处理方式 任何一个人处理信息的逻辑能力都是有限的,所以当面对一个非常复杂的问题时我们不太可能一次性搞定一大堆的内容. 但是我们人有一种天生的能力 ...

  10. Mybatis【1】-- 第一个Mybatis程序

    1.框架是什么 框架(Framework)是整个或部分系统的可重用设计,表现为一组抽象构件及构件实例间交互的方法;另一种定义认为,框架是可被应用开发者定制的应用骨架.前者是从应用方面而后者是从目的方面 ...