springboot整合tobato的fastdfs实现⽂件上传和下载添加项⽬所需要的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- taobao fastdfs依赖 -->
<dependency>
<groupId>bato</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.apachemons</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 bato.fastdfs.FdfsClientConfig;
import t.annotation.Configuration;
import t.annotation.EnableMBeanExport;
import t.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 t.annotation.Bean;
import t.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("st.fastdfs"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("SpringBoot利⽤Swagger构建API⽂档")
.
description("使⽤RestFul风格, 创建⼈:知了⼀笑")
.termsOfServiceUrl("i-betablogs/javaju")
.version("version 1.0")
.build();
}
}
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参数,⽀持多个,我这⾥只有⼀个,如果有多个在下⽅加- :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 bato.fastdfs.domain.fdfs.StorePath;
import bato.fastdfs.domain.proto.storage.DownloadByteArray;
import bato.fastdfs.service.FastFileStorageClient;
import org.apachemons.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 = Logger(FastDFSClientUtil.class); @Resource
private FastFileStorageClient storageClient ;
/**
* 上传⽂件
*/
public String upload(MultipartFile multipartFile) throws Exception{
String originalFilename = OriginalFilename().
OriginalFilename().
lastIndexOf(".") + 1);
StorePath storePath = this.storageClient.uploadImageAndCrtThumbImage(
FullPath() ;
}
/**
* 删除⽂件
*/
public void deleteFile(String fileUrl) {
if (StringUtils.isEmpty(fileUrl)) {
spring framework组件LOGGER.info("fileUrl == >>⽂件路径为空...");
return;
}
try {
StorePath storePath = StorePath.parseFromUrl(fileUrl);
storageClient.Group(), Path());
} catch (Exception e) {
LOGGER.Message());
}
}
/**
* 下载⽂件
*/
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 st.fastdfs.FastDFSClientUtil;
import io.swagger.annotations.ApiOperation;
import org.apachemons.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
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论