• 添加项目所需要的依赖
<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. artTemplate字符串模板

    1.官网:http://aui.github.io/art-template/

  2. 如何将python源文件打包成exe文件

    PyInstaller是一个十分有用的第三方库,它能够在Windows.Linux.Mac OS X 等操作系统下将 Python 源文件打包,通过对源文件打包,Python 程序可以在没有安装 Py ...

  3. Python模块之-OS模块

    一.os模块概述 Python os模块包含普遍的操作系统功能.如果你希望你的程序能够与平台无关的话,这个模块是尤为重要的.(一语中的) 二.常用方法 1.os.name 输出字符串指示正在使用的平台 ...

  4. jvisualvm性能监控

    一.配置JMX 1.进入tomcat bin目录 vim catalina.sh #!/bin/sh下面加入: #!/bin/sh JAVA_OPTS="-Dcom.sun.manageme ...

  5. wannafly 挑战赛8 E 小G的项链(manecher)

    链接:https://www.nowcoder.com/acm/contest/57/E 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32768K,其他语言65536K 64bit ...

  6. CentOS7修改计算机名!

    https://www.cnblogs.com/acgpiano/p/4170546.html sudo hostnamectl set-hostname <host-name>

  7. 对vi/vim的一些看法

    早在网上看到别人如何把vi吹得神乎其神了,决定试着用一下.不过还是发现太麻烦了,因为我是在windows系统下面的,网络的原因无法使用linux系统(无校园电信客户端). 首先vim只是一个文本编辑器 ...

  8. windows环境下PostgreSQL的安装

    1.首先在如下链接下载PostgreSQL的压缩包,我这里下载的是postgresql-12.1-1-windows-x64-binaries.zip. https://www.enterprised ...

  9. golang 导出CSV文件中文乱码的问题

    golang  导出CSV文件中文乱码的问题 解决办法: 在csv文件的开头写入 UTF-8 BOM // 创建文件 dstf, err := os.Create("./data/" ...

  10. C 语言的函数 - 内存分析

    函数基本概念 Linux 中,函数在内存的代码段(code 区),地址比较靠前. 函数定义 C 语言中,函数有三个要素:入参.返回值.函数名,缺一不可.函数使用前必须先声明,或者在使用之前定义. 函数 ...