FastDFS 服务搭建参考上一篇
一坨坨代码实现:
idea 新建一个 SpringBoot 项目,项目目录:
pom.xml:
<!-- Swagger2 核心依赖 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<!-- fastdfs-client -->
<dependency>
<groupId>com.github.tobato</groupId>
<artifactId>fastdfs-client</artifactId>
<version>1.26.7</version>
</dependency>
application.yml:
fdfs:
so-timeout: 3000
connect-timeout: 1000
thumb-image:
width: 60
height: 60
tracker-list:
- 192.168.132.129:22122
Swagger配置:
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.zch.fastdfs"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("SpringBoot整合FastDFS")
.version("version 0.0.1")
.build();
}
}
WebMvcConfig配置:
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
/**
* 实现静态资源的映射
*
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**")
.addResourceLocations("classpath:/META-INF/resources/");
}
}
FastDFSClientConfig:
/**
* FastDFS 配置
* @author zch
* @date 2020/12/29 17:34
*/
@Configuration
@Import(FdfsClientConfig.class)
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
public class FastDFSClientConfig {
}
FileController:
@Api(value = "文件管理", tags = {"文件相关的接口"})
@RestController
@RequestMapping("/file")
public class FileController {
@Autowired
private FastFileStorageClient storageClient;
@PostMapping("/")
@ApiOperation(value = "文件上传", httpMethod="POST")
public String uploadFile(MultipartFile file) throws IOException {
//获取文件后缀名
String[] fileNameArr = file.getOriginalFilename().split("\\.");
String suffix = fileNameArr[fileNameArr.length - 1];
StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), suffix, null);
return storePath.getFullPath();
}
@DeleteMapping("/")
@ApiOperation(value = "文件删除", httpMethod="DELETE")
public String deleteFile(String filePath) {
storageClient.deleteFile(filePath);
return "OK";
}
}
源码地址:https://github.com/hh266/to-be-a-architect/tree/master/project/fastdfs-demo
结果测试:
测试地址:http://localhost:8080/swagger-ui.html
文件上传:
根据结果拼接url,用浏览器打开:
删除文件
我就不展示了,留给大家测试吧。