• 添加项目所需要的依赖
<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 实现文件上传和下载的更多相关文章

  1. SpringBoot整合阿里云OSS文件上传、下载、查看、删除

    1. 开发前准备 1.1 前置知识 java基础以及SpringBoot简单基础知识即可. 1.2 环境参数 开发工具:IDEA 基础环境:Maven+JDK8 所用技术:SpringBoot.lom ...

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

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

  3. springboot+web文件上传和下载

    一.首先安装mysql数据库,开启web服务器. 二.pom.xml文件依赖包配置如下: <?xml version="1.0" encoding="UTF-8&q ...

  4. SpringBoot 文件上传、下载、设置大小

    本文使用SpringBoot的版本为2.0.3.RELEASE 1.上传单个文件 ①html对应的提交表单 <form action="uploadFile" method= ...

  5. SpringBoot下文件上传与下载的实现

    原文:http://blog.csdn.net/colton_null/article/details/76696674 SpringBoot后台如何实现文件上传下载? 最近做的一个项目涉及到文件上传 ...

  6. 七、springBoot 简单优雅是实现文件上传和下载

    前言 好久没有更新spring Boot 这个项目了.最近看了一下docker 的知识,后期打算将spring boot 和docker 结合起来.刚好最近有一个上传文件的工作呢,刚好就想起这个脚手架 ...

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

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

  8. 精讲响应式WebClient第4篇-文件上传与下载

    本文是精讲响应式WebClient第4篇,前篇的blog访问地址如下: 精讲响应式webclient第1篇-响应式非阻塞IO与基础用法 精讲响应式WebClient第2篇-GET请求阻塞与非阻塞调用方 ...

  9. 学习SpringMVC必知必会(7)~springmvc的数据校验、表单标签、文件上传和下载

    输入校验是 Web 开发任务之一,在 SpringMVC 中有两种方式可以实现,分别是使用 Spring 自带的验证 框架和使用 JSR 303 实现, 也称之为 spring-validator 和 ...

随机推荐

  1. Python 3标准库第一天讲解总结

    一.很多知识自己没有理解透: 二.课件准备不足: 三.第一次讲解有点紧张: 四.口才也不是很好,很多有断片的情况: 五.SB式的坚持:

  2. Fiddler的工作原理与主菜单介绍(一)

    1.简介: 官网:https://www.telerik.com/fiddler Fiddler是比较好用的web代理调试工具之一,它能记录并检查所有客户端与服务端的HTTP/HTTPS请求,能够设置 ...

  3. guava缓存第一篇

    guava缓存主要有2个接口,Cache和LoadingCache. Cache,全类名是com.google.common.cache.Cache,支持泛型.Cache<K, V>. L ...

  4. 【BZOJ5249】IIIDX(贪心,线段树)

    题意: 思路:赛季结束之前余总推荐的一道好题,不愧是余总 From https://www.cnblogs.com/suika/p/8748115.html 简略的说就是在预留足够多的位置的前提下贪心 ...

  5. 2019.9.23JAVA动手动脑

    1请看以下代码,你发现了有什么特殊之处吗? // MethodOverload.java// Using overloaded methods public class MethodOverload ...

  6. Selenium 控制浏览器

    webdriver提供了操作浏览器的一些基本方法,例如:打开,前进,后退,刷新,设置窗口大小,截屏,退出等 一.打开网页 代码: # coding = utf-8 from time import s ...

  7. Spring Cloud Stream教程(二)主要概念

    Spring Cloud Stream提供了一些简化了消息驱动的微服务应用程序编写的抽象和原语.本节概述了以下内容: Spring Cloud Stream的应用模型 Binder抽象 持续的发布 - ...

  8. Java中参数的引用传递和值传递

    1.一些定义 值传递:把实际传入参数的值,在内存中赋值一份 引用传递:传入的是实际参数的地址 2.传递基本类型的参数 因为Java是值传递,那就不难理解下面的代码不交换任何值 swap(Type ar ...

  9. centos7 升级gcc9.1.0版本

    centos7 环境 查缺补漏 yum install gcc gcc-c++ -y yum install bzip2 -y gcc版本下载:https://gcc.gnu.org/mirrors. ...

  10. html初体验#1

    html的一些自见解 html 5 自带语义化,就是让标签带上感情色彩,方便人或浏览器区分 <b></b>与<strong></strong>的区别 & ...