1.pom依赖
io.springfox
springfox-swagger2
2.9.2
com.github.xiaoymin
swagger-bootstrap-ui
1.9.2
org.projectlombok
lombok
com.github.xiaoymin
knife4j-annotations
2.0.4
2.yml配置
##文件上传根路径
upload-file:
base-path: D:/file/report/
http-url: http://127.0.0.1:56743/
#swagger公共信息
swagger:
title: 接口文档系统
description: 接口文档系统
version: 2.8.0.RELEASE
license: Powered By kkp
license-url:
terms-of-service-url:
contact:
name:
email:
url:
#knife4j配置
knife4j:
#启用
enable: true
#基础认证
basic:
enable: false
username: blade
password: blade
3.Swagger2Config
package com.example.demo1;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ClassUtils;
import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.documentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class Swagger2Config {
@Bean
public Docket customDocket(){
return new Docket(documentationType.SWAGGER_2)
.apiInfo(apiInfo())
.groupName("业务模块")
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo1.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
Contact contact = new Contact("Scarlet-Max", "https://blog.csdn.net/weixin_44907173/article/details/121633828?spm=1001.2014.3001.5501", "592566477@qq.com");
return new ApiInfoBuilder()
.title("Scarlet-Max API接口")//标题
.description("API接口的描述")//文档接口的描述
.contact(contact)
.version("1.1.0")//版本号
.build();
}
}
4.DemoController
package com.example.demo1.controller;
import com.example.demo1.entity.FileModuleEnum;
import com.example.demo1.entity.Result;
import com.example.demo1.entity.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.validation.Valid;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
@RestController
@RequestMapping("test/demo")
@Api(tags = "swagger测试")
@Slf4j
public class DemoController {
@Value("${upload-file.base-path}")
private String uploadFilePath;
@Value("${upload-file.http-url}")
private String fileHttpUrl;
// 根据项目需要自行修改
private long pathId = 110;
// 总文件加名称
private static long tenantId = 1;
@GetMapping("/test1")
@ApiImplicitParams({
@ApiImplicitParam(name = "页数", value = "page", defaultValue = "1", required = true, dataType = "int"),
@ApiImplicitParam(name = "数量", value = "limit", defaultValue = "10", required = true, dataType = "int")
})
@ApiOperation(value = "产品列表1", notes = "产品列表")
public String getTest(@RequestParam(required = true) Map param) {
return "test1";
}
@PostMapping("/test2")
@ApiImplicitParams({
@ApiImplicitParam(name = "页数", value = "page", defaultValue = "1", required = true, dataType = "int"),
@ApiImplicitParam(name = "数量", value = "limit", defaultValue = "10", required = true, dataType = "int")
})
@ApiOperation(value = "产品列表2", notes = "产品列表")
public String getTest2(@RequestParam(required = true) Map param) {
return "产品列表2";
}
@ApiOperation(value = "文件上传")
@ApiImplicitParams({
@ApiImplicitParam(name = "file", value = "文件", required = true, dataType = "String", paramType = "query"),
@ApiImplicitParam(name = "module", value = "(0默认、1其他)", required = false, dataType = "int", paramType = "query")
})
@PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public Result uploadFile(@RequestParam("file") MultipartFile file, @RequestParam(value = "module", required = false) Integer module) throws Exception {
FileOutputStream fos = null;
try {
//
StringBuilder filePathFix = new StringBuilder(FileModuleEnum.getModule(module));
filePathFix.append(tenantId).append(File.separator).append(pathId).append(File.separator);
// 文件上传路径
StringBuilder filePath = new StringBuilder();
if (uploadFilePath.equals(File.separator)){
filePath.append(uploadFilePath).append(filePathFix);
}else {
filePath.append(uploadFilePath).append(File.separator).append(filePathFix);
}
//查询文件是否存在
File targetPath = new File(filePath.toString());
if (!targetPath.exists()) {
targetPath.mkdirs();
}
String fileName = UUID.randomUUID() + file.getOriginalFilename();
fos = new FileOutputStream(filePath.toString() + fileName);
//写入文件
IOUtils.copy(file.getInputStream(), fos);
//获取文件访问路径
StringBuilder url = new StringBuilder();
if (fileHttpUrl.endsWith(File.separator)) {
url.append(fileHttpUrl)
.append(filePathFix.toString())
.append(fileName);
} else {
url.append(fileHttpUrl)
.append(File.separator)
.append(filePathFix.toString())
.append(fileName);
}
return Result.succeed(url.toString(), "上传成功");
} catch (Exception e) {
throw new Exception(e.getMessage());
}finally {
try{
if(fos != null){
fos.close();
}
}catch(Exception e){
log.error("关闭输出流错误!", e);
}
}
}
@ApiOperation(value = "删除附件")
@ApiImplicitParams({
@ApiImplicitParam(name="fileName" ,value="附件名称" ,required=true ,dataType="String",paramType="query"),
@ApiImplicitParam(name="module" ,value="(0默认、1其他)" ,required=false ,dataType="int",paramType="query")
})
@PostMapping(value = "/delFile", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public Result delFile(@RequestParam("fileName") String fileName,@RequestParam(value = "module",required = false) Integer module) throws Exception {
FileOutputStream fos = null;
try {
StringBuilder filePathSuffix = new StringBuilder(FileModuleEnum.getModule(module));
filePathSuffix.append(tenantId)
.append(File.separator)
.append(pathId)
.append(File.separator);
//文件上传路径
StringBuilder filePaths = new StringBuilder();
if (uploadFilePath.endsWith(File.separator)) {
filePaths.append(uploadFilePath)
.append(filePathSuffix);
} else {
filePaths.append(uploadFilePath)
.append(File.separator)
.append(filePathSuffix)
.append(fileName);
}
File targetPath = new File(filePaths.toString());
if (targetPath.exists()) {
targetPath.delete();
return Result.succeed("删除附件成功");
}
return Result.failed("文件不存在");
}catch (Exception e){
throw new Exception(e.getMessage());
}finally {
try{
if(fos != null){
fos.close();
}
}catch(Exception e){
log.error("关闭输出流错误!", e);
}
}
}
@ApiOperation(value = "test3")
@PostMapping("/save")
public String test3(@Valid @RequestBody User user){
return "11111111111111111";
}
}
5.User
package com.example.demo1.entity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.validation.constraints.NotBlank;
import java.io.Serializable;
@Data
@ApiModel(value = "对象", description = "对象")
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {
@ApiModelProperty(value = "名称")
@NotBlank(message = "name不为空")
private String name;
@ApiModelProperty(value = "性别")
@NotBlank(message = "sex不为空")
private String sex;
@ApiModelProperty(value = "年龄")
private int age;
}
6.EnumCode
package com.example.demo1.entity;
public enum EnumCode {
SUCCESS(0),
ERROR(1);
private Integer code;
EnumCode(Integer code) {
this.code = code;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}
7.FileModuleEnum
package com.example.demo1.entity;
import java.io.File;
public enum FileModuleEnum {
FINANCE(1,"sss");
private String module;
private int index;
FileModuleEnum(int index,String module) {
this.index = index;
this.module = module;
}
public static String getModule(Integer index) {
if(null != index){
FileModuleEnum[] modules = values();
for (FileModuleEnum module : modules) {
if (module.index == index) {
return module.module + File.separator;
}
}
}
return "";
}
}
8.Result
package com.example.demo1.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; @Data @NoArgsConstructor @AllArgsConstructor public class Resultimplements Serializable { private T datas; private Integer code; private String msg; public static Result succeed(String msg) { return succeedWith(null, EnumCode.SUCCESS.getCode(),msg); } public static Result succeed(T model, String msg) { return succeedWith(model, EnumCode.SUCCESS.getCode(),msg); } public static Result succeedWith(T datas, Integer code,String msg) { return new Result (datas, code, msg); } public static Result failed(String msg) { return failedWith(null, EnumCode.ERROR.getCode(), msg); } public static Result failed(T model,String msg) { return failedWith(model, EnumCode.ERROR.getCode(), msg); } public static Result failedWith(T datas, Integer code, String msg) { return new Result ( datas, code, msg); } }



