springboot 整合 tobato 的 fastdfs 实现文件上传和下载
- 添加项目所需要的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- taobao fastdfs依赖 -->
<dependency>
<groupId>com.github.tobato</groupId>
<artifactId>fastdfs-client</artifactId>
<version>1.26.5</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
<!-- Swagger2 核心依赖 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
- 引入 FastDFS 配置
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) // 导入FastDFS-Client组件
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING) // 解决jmx重复注册bean的问题
public class FdfsConfiguration {
}
- 引入 swaggerUI 配置
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket; @Configuration
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.xuecheng.test.fastdfs"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("SpringBoot利用Swagger构建API文档")
.description("使用RestFul风格, 创建人:知了一笑")
.termsOfServiceUrl("https://i-beta.cnblogs.com/javaju")
.version("version 1.0")
.build();
}
}
- application.yml
server:
port: 8011 # 分布式文件系统FDFS配置
fdfs:
soTimeout: 1500 #socket连接超时时长
connectTimeout: 600 #连接tracker服务器超时时长
reqHost: 192.168.133.131 #nginx访问地址
reqPort: 80 #nginx访问端口
thumbImage: #缩略图生成参数,可选
width: 150
height: 150
trackerList: #TrackerList参数,支持多个,我这里只有一个,如果有多个在下方加- x.x.x.x:port
- 192.168.133.131:22122
- 192.168.133.131:22122
spring:
application:
name: ware-fast-dfs
servlet:
multipart:
enabled: true
max-file-size: 10MB
max-request-size: 20MB
- FastDFSCilentUtil
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile; import javax.annotation.Resource;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException; @Component
public class FastDFSClientUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(FastDFSClientUtil.class);
@Resource
private FastFileStorageClient storageClient ;
/**
* 上传文件
*/
public String upload(MultipartFile multipartFile) throws Exception{
String originalFilename = multipartFile.getOriginalFilename().
substring(multipartFile.getOriginalFilename().
lastIndexOf(".") + 1);
StorePath storePath = this.storageClient.uploadImageAndCrtThumbImage(
multipartFile.getInputStream(),
multipartFile.getSize(),originalFilename , null);
return storePath.getFullPath() ;
}
/**
* 删除文件
*/
public void deleteFile(String fileUrl) {
if (StringUtils.isEmpty(fileUrl)) {
LOGGER.info("fileUrl == >>文件路径为空...");
return;
}
try {
StorePath storePath = StorePath.parseFromUrl(fileUrl);
storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
} catch (Exception e) {
LOGGER.info(e.getMessage());
}
} /**
* 下载文件
*/
public byte[] downloadFile(String fileUrl){
String group = fileUrl.substring(0, fileUrl.indexOf("/"));
String path = fileUrl.substring(fileUrl.indexOf("/") + 1);
DownloadByteArray downloadByteArray = new DownloadByteArray();
byte[] bytes = this.storageClient.downloadFile(group, path, downloadByteArray);
try {
//将文件保存到d盘
FileOutputStream fileOutputStream = new FileOutputStream("d:\\911565.png");
fileOutputStream.write(bytes);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bytes;
}
}
- FileController
import com.juju.test.fastdfs.FastDFSClientUtil;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile; import javax.annotation.Resource; @RestController
public class FileController {
@Resource
private FastDFSClientUtil fileDfsUtil ;
/**
* 文件上传
*/
@ApiOperation(value="上传文件", notes="测试FastDFS文件上传")
@RequestMapping(value = "/uploadFile",headers="content-type=multipart/form-data", method = RequestMethod.POST)
public ResponseEntity<String> uploadFile (@RequestParam("file") MultipartFile file){
String result ;
try{
String path = fileDfsUtil.upload(file) ;
if (!StringUtils.isEmpty(path)){
result = path ;
} else {
result = "上传失败" ;
}
} catch (Exception e){
e.printStackTrace() ;
result = "服务异常" ;
}
return ResponseEntity.ok(result);
}
/**
* 文件删除
*/
@RequestMapping(value = "/deleteByPath", method = RequestMethod.GET)
public ResponseEntity<String> deleteByPath (){
String filePathName = "group1/M00/00/00/wKhIgl0n4AKABxQEABhlMYw_3Lo825.png" ;
fileDfsUtil.deleteFile(filePathName);
return ResponseEntity.ok("SUCCESS") ;
} @ApiOperation(value="下载文件", notes="测试FastDFS文件下载")
@GetMapping("/downloadFile")
public ResponseEntity<String> downloadFile(){
String g = "group1/M00/00/00/wKiFg13Plc6AVz_hAB6IzmlNPeY944.png";
byte[] bytes = fileDfsUtil.downloadFile(g);
System.out.println(bytes);
return ResponseEntity.ok("SUCCESS");
}
}
- springboot启动类
@SpringBootApplication
//Swaggerui注解
@EnableSwagger2
public class TestFastDFSApplication {
public static void main(String[] args) {
SpringApplication.run(TestFastDFSApplication.class,args); }
}
- 启动并访问 localhost:8011/swagger-ui.html 进行测试

- 点击 Try it out!

返回文件存储在 FastDFS服务器上的 url 地址
2019-11-16
springboot 整合 tobato 的 fastdfs 实现文件上传和下载的更多相关文章
- SpringBoot整合阿里云OSS文件上传、下载、查看、删除
1. 开发前准备 1.1 前置知识 java基础以及SpringBoot简单基础知识即可. 1.2 环境参数 开发工具:IDEA 基础环境:Maven+JDK8 所用技术:SpringBoot.lom ...
- FastDFS实现文件上传下载实战
正好,淘淘商城讲这一块的时候,我又想起来当时老徐让我写过一个关于实现FastDFS实现文件上传下载的使用文档,当时结合我们的ITOO的视频系统和毕业论文系统,整理了一下,有根据网上查到的知识,总结了一 ...
- springboot+web文件上传和下载
一.首先安装mysql数据库,开启web服务器. 二.pom.xml文件依赖包配置如下: <?xml version="1.0" encoding="UTF-8&q ...
- SpringBoot 文件上传、下载、设置大小
本文使用SpringBoot的版本为2.0.3.RELEASE 1.上传单个文件 ①html对应的提交表单 <form action="uploadFile" method= ...
- SpringBoot下文件上传与下载的实现
原文:http://blog.csdn.net/colton_null/article/details/76696674 SpringBoot后台如何实现文件上传下载? 最近做的一个项目涉及到文件上传 ...
- 七、springBoot 简单优雅是实现文件上传和下载
前言 好久没有更新spring Boot 这个项目了.最近看了一下docker 的知识,后期打算将spring boot 和docker 结合起来.刚好最近有一个上传文件的工作呢,刚好就想起这个脚手架 ...
- Java 客户端操作 FastDFS 实现文件上传下载替换删除
FastDFS 的作者余庆先生已经为我们开发好了 Java 对应的 SDK.这里需要解释一下:作者余庆并没有及时更新最新的 Java SDK 至 Maven 中央仓库,目前中央仓库最新版仍旧是 1.2 ...
- 精讲响应式WebClient第4篇-文件上传与下载
本文是精讲响应式WebClient第4篇,前篇的blog访问地址如下: 精讲响应式webclient第1篇-响应式非阻塞IO与基础用法 精讲响应式WebClient第2篇-GET请求阻塞与非阻塞调用方 ...
- 学习SpringMVC必知必会(7)~springmvc的数据校验、表单标签、文件上传和下载
输入校验是 Web 开发任务之一,在 SpringMVC 中有两种方式可以实现,分别是使用 Spring 自带的验证 框架和使用 JSR 303 实现, 也称之为 spring-validator 和 ...
随机推荐
- 【转】Linux逻辑卷管理
一. 前言 LVM是逻辑卷管理(Logical Volume Manager)的简称,它是建立在物理存储设备之上的一个抽象层,允许你生成逻辑存储卷,与直接使用物理存储在管理上相比,提供了更好灵活性.L ...
- hdu 3376 : Matrix Again【MCMF】
题目链接 题意:给定一个n*n的矩阵,找一条路,从左上角到右下角再到左上角,每个点最多经过一次,求路径上的点的权值的最大和. 将矩阵中每个点拆点,点容量为1,费用为点权值的相反数.每个点向自己右侧和下 ...
- 算法复习_线性时间求解Majority Vote Algorithm问题
题目来源于Leecode上的Majority Element问题 Majority Element:在一个序列中出现了至少n/2的下界次 使用排序算法取中位数则需要Nlogn http://www.c ...
- 2019春Python程序设计作业1(0319-0325)
判断题 1-1 在Python 3.x中可以使用中文作为变量名. (2分) T F Python变量使用前必须先声明,并且一旦声明就不能再当前作用域内改变其类型.(2分) T ...
- HDU 1394 Minimum Inversion Number (树状数组 && 规律 && 逆序数)
题意 : 有一个n个数的数列且元素都是0~n-1,问你将数列的其中某一个数及其前面的数全部置到后面这种操作中(比如3 2 1 0中选择第二个数倒置就产生1 0 3 2)能产生的最少的逆序数对是多少? ...
- 论文阅读:Stateless Network Functions: Breaking the Tight Coupling of State and Processing
摘要: 无状态网络功能是一个新的网络功能虚拟化架构,解耦了现有的网络功能设计到无状态处理组件以及数据存储层,在打破紧密耦合的同时,实现了更具可伸缩性和可恢复性的网络功能基础设施.无状态NF处理实例是围 ...
- intellij idea中去除@Autowired注入对象的红色波浪线提示
idea中通过@Autowired注入的对象一直有下划线提示. 解决:改变@Autowired的检查级别即可. 快捷键:Ctrl+Alt+s,进入idea设置界面,输入inspections检索
- 实验报告二&第四周学习总结
一.实验目的: (1) 掌握类的定义,熟悉属性.构造函数.方法的调用,掌握用类作为类型声明变量和方法返回值: (2) 理解类和对象的区别,掌握构造函数的使用,熟悉通过对象名引用实例的方法和属性: (3 ...
- 【机器学习速成宝典】模型篇02线性回归【LR】(Python版)
目录 什么是线性回归 最小二乘法 一元线性回归 多元线性回归 什么是规范化 Python代码(sklearn库) 什么是线性回归(Linear regression) 引例 假设某地区租房价格只与房屋 ...
- 使用collection:分段查询结果集
1.在人员接口书写方法 public List<Employee> getEmpsByDeptId(Integer deptId); 2在人员映射文件中进行配置 <!-- publi ...