两种方式上传,一种是Minio文件服务器,一种是Nginx下静态资源服务器(未完)

架构层次

image.png

yml

  1. server:
  2. port: 8082
  3. spring:
  4. servlet:
  5. multipart:
  6. max-file-size: 500MB
  7. max-request-size: 500MB
  8. ## Mysql
  9. # datasource:
  10. # url: jdbc:mysql://192.168.10.223:3306/sjtc_bz_db?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF8&zeroDateTimeBehavior=convertToNull
  11. # username: root
  12. # password: dca282e70e
  13. # driver-class-name: com.mysql.jdbc.Driver
  14. # Oracle
  15. datasource:
  16. url: jdbc:oracle:thin:@192.168.10.223:1522/ORCLPDB1
  17. username: SJTC_BZ_DB
  18. password: 123456
  19. type: com.alibaba.druid.pool.DruidDataSource
  20. driver-class-name: oracle.jdbc.OracleDriver

pom

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <parent>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-parent</artifactId>
  8. <version>2.5.1</version>
  9. <relativePath/> <!-- lookup parent from repository -->
  10. </parent>
  11. <groupId>com.example</groupId>
  12. <artifactId>demo</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>demo</name>
  15. <description>Demo project for Spring Boot</description>
  16. <properties>
  17. <java.version>1.8</java.version>
  18. <springfox.version>2.7.0</springfox.version>
  19. <mysql.version>5.1.40</mysql.version>
  20. <mybatisplus.version>2.1.0</mybatisplus.version>
  21. <mybatisplus-spring-boot-starter.version>1.0.4</mybatisplus-spring-boot-starter.version>
  22. </properties>
  23. <dependencies>
  24. <dependency>
  25. <groupId>org.springframework.boot</groupId>
  26. <artifactId>spring-boot-starter-web</artifactId>
  27. </dependency>
  28. <dependency>
  29. <groupId>org.springframework.boot</groupId>
  30. <artifactId>spring-boot-starter-test</artifactId>
  31. <scope>test</scope>
  32. </dependency>
  33. <dependency>
  34. <groupId>io.minio</groupId>
  35. <artifactId>minio</artifactId>
  36. <version>8.2.2</version>
  37. </dependency>
  38. <dependency>
  39. <groupId>org.projectlombok</groupId>
  40. <artifactId>lombok</artifactId>
  41. <version>1.18.12</version>
  42. <scope>compile</scope>
  43. </dependency>
  44. <dependency>
  45. <groupId>io.springfox</groupId>
  46. <artifactId>springfox-swagger2</artifactId>
  47. <version>${springfox.version}</version>
  48. <exclusions>
  49. <exclusion>
  50. <groupId>org.mapstruct</groupId>
  51. <artifactId>mapstruct</artifactId>
  52. </exclusion>
  53. </exclusions>
  54. </dependency>
  55. <dependency>
  56. <groupId>io.springfox</groupId>
  57. <artifactId>springfox-swagger2</artifactId>
  58. <version>2.9.2</version>
  59. </dependency>
  60. <dependency>
  61. <groupId>io.springfox</groupId>
  62. <artifactId>springfox-swagger-ui</artifactId>
  63. <version>2.9.2</version>
  64. </dependency>
  65. <dependency>
  66. <groupId>mysql</groupId>
  67. <artifactId>mysql-connector-java</artifactId>
  68. <version>${mysql.version}</version>
  69. </dependency>
  70. <!-- mybatis-plus begin -->
  71. <dependency>
  72. <groupId>org.springframework.boot</groupId>
  73. <artifactId>spring-boot-starter-jdbc</artifactId>
  74. </dependency>
  75. <dependency>
  76. <groupId>com.baomidou</groupId>
  77. <artifactId>mybatisplus-spring-boot-starter</artifactId>
  78. <version>${mybatisplus-spring-boot-starter.version}</version>
  79. </dependency>
  80. <dependency>
  81. <groupId>com.baomidou</groupId>
  82. <artifactId>mybatis-plus</artifactId>
  83. <version>${mybatisplus.version}</version>
  84. </dependency>
  85. <dependency>
  86. <groupId>com.oracle.ojdbc</groupId>
  87. <artifactId>ojdbc8</artifactId>
  88. </dependency>
  89. <dependency>
  90. <groupId>com.alibaba</groupId>
  91. <artifactId>fastjson</artifactId>
  92. <version>1.2.9</version>
  93. </dependency>
  94. <!-- druid 连接池-->
  95. <dependency>
  96. <groupId>com.alibaba</groupId>
  97. <artifactId>druid</artifactId>
  98. <version>1.1.10</version>
  99. </dependency>
  100. </dependencies>
  101. <build>
  102. <plugins>
  103. <plugin>
  104. <groupId>org.springframework.boot</groupId>
  105. <artifactId>spring-boot-maven-plugin</artifactId>
  106. </plugin>
  107. </plugins>
  108. </build>
  109. </project>

config

MinioConfig

  1. public class MinioConfig {
  2. /**
  3. * ip+port
  4. */
  5. public static String Url = "http://192.168.10.223:9002";
  6. public static String AccessKey = "orisdom";
  7. public static String SecretKey = "orisdom123";
  8. public static String BucketName = "sjtc";
  9. }

SimpleConfig

  1. public class SimpleConfig {
  2. /**
  3. * 本地文件保存根路径
  4. */
  5. /**
  6. * ip+port
  7. */
  8. public static String Url = "";
  9. public static String localPath = "";
  10. }

enums

FileType

  1. public enum FileType {
  2. 文本("0"),图片("1"),视频("2");
  3. private final String type;
  4. FileType(String type){
  5. this.type = type;
  6. }
  7. public String getType() {
  8. return type;
  9. }
  10. }

UploadType

  1. public enum UploadType {
  2. 上传本地("normal"),上传Minio("minio");
  3. private final String type;
  4. UploadType(String type){
  5. this.type = type;
  6. }
  7. public String getType() {
  8. return type;
  9. }
  10. }

entity

FileEntity

  1. /**
  2. * @author: Jili
  3. * @description: com.orisdom.modules.common.entity
  4. * @date: Created on 2021/9/1 10:33
  5. */
  6. @NoArgsConstructor
  7. @AllArgsConstructor
  8. @Builder
  9. @Data
  10. @ApiModel(description = "文件上传")
  11. @TableName("C_FILES")
  12. public class FileEntity implements Serializable{
  13. private static final long serialVersionUID = 1L;
  14. @ApiModelProperty(value = "文件ID")
  15. @TableId(value = "FILE_ID", type = IdType.UUID)
  16. private String fileId;
  17. @ApiModelProperty(value = "文件名称")
  18. @TableField("FILE_NAME")
  19. private String fileName;
  20. @ApiModelProperty(value = "类型")
  21. @TableField("FILE_TYPE")
  22. private String fileType;
  23. @ApiModelProperty(value = "拓展名")
  24. @TableField("EXT")
  25. private String ext;
  26. @ApiModelProperty(value = "文件在磁盘中的存储名称,不包含路径和扩展名")
  27. @TableField("STORAGE_NAME")
  28. private String storageName;
  29. @ApiModelProperty(value = "文件大小")
  30. @TableField("FILE_SIZE")
  31. private Double fileSize;
  32. @TableField("URI")
  33. private String uri;
  34. @TableField("URL")
  35. private String url;
  36. @TableField("INSERT_USER")
  37. private String insertUser;
  38. @TableField("LAST_UPDATE_USER")
  39. private String lastUpdateUser;
  40. @TableField("INSERT_DATETIME")
  41. private Date insertDatetime;
  42. @TableField("LAST_UPDATE_TIME")
  43. private Date lastUpdateTime;
  44. }

service

IFileService

  1. public interface IFileService {
  2. /**
  3. * @return
  4. */
  5. // String upload(MultipartFile file, FileType fileType, UploadType uploadType);
  6. /**
  7. * MultipartFile
  8. * @param file 上传文件
  9. * @param bucketName 桶名
  10. * @param fileName 文件保存新名字
  11. * @param uploadType 上传方式
  12. * @return
  13. */
  14. String upload(MultipartFile file, String bucketName, String fileName,UploadType uploadType);
  15. /**
  16. * File
  17. * @param file 上传文件
  18. * @param fileType 文件类型
  19. * @param uploadType 上传方式
  20. * @return
  21. */
  22. String upload(File file, FileType fileType, UploadType uploadType) throws Exception;
  23. }

FileService

  1. @Service
  2. public class FileService implements IFileService {
  3. // @Override
  4. // public String upload(MultipartFile file, FileType fileType, UploadType uploadType) {
  5. // String url = null;
  6. // switch (uploadType) {
  7. // case 上传本地:
  8. // url = SimpleFileUtil.getInstance().upload(file, fileType);
  9. // break;
  10. // case 上传Minio:
  11. // url = MinioFileUtil.getInstance().upload(MinioConfig.BucketName, file);
  12. // break;
  13. // default:
  14. // break;
  15. // }
  16. // return url;
  17. // }
  18. /*
  19. 改良版
  20. */
  21. @Override
  22. public String upload(MultipartFile file, String bucketName, String fileName,UploadType uploadType) {
  23. String url = null;
  24. switch (uploadType) {
  25. case 上传本地:
  26. url = SimpleFileUtil.getInstance().upload(file, fileName);
  27. break;
  28. case 上传Minio:
  29. url = MinioFileUtil.getInstance().upload(file,bucketName,fileName);
  30. break;
  31. default:
  32. break;
  33. }
  34. return url;
  35. }
  36. @Override
  37. public String upload(File file, FileType fileType, UploadType uploadType) throws Exception {
  38. FileInputStream inputStream = new FileInputStream(file);
  39. String url = null;
  40. switch (uploadType) {
  41. case 上传本地:
  42. url = SimpleFileUtil.getInstance().upload(inputStream, file.getName(), fileType);
  43. break;
  44. case 上传Minio:
  45. url = MinioFileUtil.getInstance().upload(fileType.getType(), file.getName(), inputStream);
  46. break;
  47. default:
  48. break;
  49. }
  50. return url;
  51. }
  52. }

util

MinioFileUtil

  1. @Service
  2. public class FileService implements IFileService {
  3. // @Override
  4. // public String upload(MultipartFile file, FileType fileType, UploadType uploadType) {
  5. // String url = null;
  6. // switch (uploadType) {
  7. // case 上传本地:
  8. // url = SimpleFileUtil.getInstance().upload(file, fileType);
  9. // break;
  10. // case 上传Minio:
  11. // url = MinioFileUtil.getInstance().upload(MinioConfig.BucketName, file);
  12. // break;
  13. // default:
  14. // break;
  15. // }
  16. // return url;
  17. // }
  18. /*
  19. 改良版
  20. */
  21. @Override
  22. public String upload(MultipartFile file, String bucketName, String fileName,UploadType uploadType) {
  23. String url = null;
  24. switch (uploadType) {
  25. case 上传本地:
  26. url = SimpleFileUtil.getInstance().upload(file, fileName);
  27. break;
  28. case 上传Minio:
  29. url = MinioFileUtil.getInstance().upload(file,bucketName,fileName);
  30. break;
  31. default:
  32. break;
  33. }
  34. return url;
  35. }
  36. @Override
  37. public String upload(File file, FileType fileType, UploadType uploadType) throws Exception {
  38. FileInputStream inputStream = new FileInputStream(file);
  39. String url = null;
  40. switch (uploadType) {
  41. case 上传本地:
  42. url = SimpleFileUtil.getInstance().upload(inputStream, file.getName(), fileType);
  43. break;
  44. case 上传Minio:
  45. url = MinioFileUtil.getInstance().upload(fileType.getType(), file.getName(), inputStream);
  46. break;
  47. default:
  48. break;
  49. }
  50. return url;
  51. }
  52. }

更多可以参考 https://blog.csdn.net/hzw2312/article/details/106078390

SimpleFileUtil

  1. public class SimpleFileUtil {
  2. private static SimpleFileUtil instance = new SimpleFileUtil();
  3. private SimpleFileUtil(){};
  4. public static SimpleFileUtil getInstance() {
  5. return instance;
  6. }
  7. /**
  8. * 上传文件
  9. * @param multipartFile 文件
  10. * @param fileFullName 文件相对路径 如:/images/demo.jpg
  11. * @return
  12. */
  13. @SneakyThrows(Exception.class)
  14. public String upload(MultipartFile multipartFile, String fileFullName){
  15. // String dirPath;
  16. // DateFormatter formatter = new DateFormatter();
  17. // formatter.setPattern("yyyyMMdd");
  18. // String dateSuffix = formatter.print(new Date(), Locale.CHINESE);
  19. // dirPath = SimpleConfig.localPath+"/"+type.getType()+"/"+dateSuffix;
  20. // String originalFilename = multipartFile.getOriginalFilename();
  21. // String fileName = type.getType() + "_" +
  22. // System.currentTimeMillis() +
  23. // originalFilename.substring(originalFilename.lastIndexOf("."));
  24. // Path path = Paths.get(dirPath,fileName);
  25. // Set<PosixFilePermission> permissions = PosixFilePermissions.fromString("r-xr-----");
  26. // FileAttribute<Set<PosixFilePermission>> fileAttributes = PosixFilePermissions.asFileAttribute(permissions);
  27. String dirPath = fileFullName.substring(0,fileFullName.lastIndexOf("/"));
  28. String fileName = fileFullName.substring(fileFullName.lastIndexOf("/")+1);
  29. Path path = Paths.get(dirPath,fileName);
  30. boolean dirExist = Files.exists(Paths.get(dirPath));
  31. if (!dirExist){
  32. Files.createDirectories(Paths.get(dirPath));
  33. }
  34. boolean fileExist = Files.exists(path);
  35. if (!fileExist) {
  36. Files.createFile(path);
  37. }
  38. Files.copy(multipartFile.getInputStream(),path, StandardCopyOption.REPLACE_EXISTING);
  39. return SimpleConfig.Url+fileFullName;
  40. }
  41. /**
  42. * 上传文件
  43. * @param inputStream 文件输入流
  44. * @param oriFileName 文件名称
  45. * @param type 文件类型
  46. * @return
  47. */
  48. @SneakyThrows(Exception.class)
  49. public String upload(InputStream inputStream,String oriFileName, FileType type){
  50. String dirPath;
  51. DateFormatter formatter = new DateFormatter();
  52. formatter.setPattern("yyyyMMdd");
  53. String dateSuffix = formatter.print(new Date(), Locale.CHINESE);
  54. dirPath = SimpleConfig.localPath+"/"+type.getType()+"/"+dateSuffix;
  55. String fileName = type.getType() + "_" +
  56. System.currentTimeMillis() +
  57. oriFileName.substring(oriFileName.lastIndexOf("."));
  58. Path path = Paths.get(dirPath,fileName);
  59. // Set<PosixFilePermission> permissions = PosixFilePermissions.fromString("r-xr-----");
  60. // FileAttribute<Set<PosixFilePermission>> fileAttributes = PosixFilePermissions.asFileAttribute(permissions);
  61. boolean dirExist = Files.exists(Paths.get(dirPath));
  62. if (!dirExist){
  63. Files.createDirectories(Paths.get(dirPath));
  64. }
  65. boolean fileExist = Files.exists(path);
  66. if (!fileExist) {
  67. Files.createFile(path);
  68. }
  69. Files.copy(inputStream,path, StandardCopyOption.REPLACE_EXISTING);
  70. return this.getFilePath(type, path.toString());
  71. }
  72. /**
  73. * 获取相对路径
  74. *
  75. * @param absolutePath
  76. * @return
  77. */
  78. private String getFilePath(FileType type, String absolutePath) {
  79. absolutePath = absolutePath.replace("\\", "/");
  80. int imagePathLength = SimpleConfig.localPath.length();
  81. String path;
  82. if (absolutePath.length() > imagePathLength) {
  83. path = absolutePath.substring(imagePathLength + 1, absolutePath.length());
  84. } else {
  85. path = absolutePath.substring(imagePathLength, absolutePath.length());
  86. }
  87. return path;
  88. }
  89. }

mapper
FileMapper

  1. public interface FileMapper extends BaseMapper<FileEntity> {
  2. }

Demo 接口测试

controller

  1. @RestController
  2. public class FileController {
  3. @Autowired
  4. IFileService fileService;
  5. @Autowired
  6. FileMapper fileMapper;
  7. private static final Logger log = LoggerFactory.getLogger(FileController.class);
  8. @PostMapping("/test")
  9. @ApiOperation(value = "文件上传", response = String.class)
  10. public void test(@RequestParam("file") MultipartFile file, HttpServletRequest req) {
  11. if (file.isEmpty()) {
  12. // return "请选择文件!";
  13. } else {
  14. SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
  15. String date = sdf.format(new Date());
  16. String path="/"+date+"/"+UUID.randomUUID().toString().replace("-","")+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
  17. SimpleConfig.Url="116.62.41.96:8081";
  18. SimpleConfig.localPath="/images";
  19. String fileName = SimpleConfig.Url+SimpleConfig.localPath+path;
  20. String url =fileService.upload(file,"",path,UploadType.上传本地);
  21. System.out.println(url);
  22. }
  23. }
  24. @PostMapping("/upload")
  25. @ApiOperation(value = "文件上传", response = String.class)
  26. public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest req) {
  27. if (file.isEmpty()) {
  28. return "请选择文件!";
  29. } else {
  30. SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
  31. String date = sdf.format(new Date());
  32. String fileName=date+"/"+UUID.randomUUID().toString().replace("-","")+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
  33. String url=fileService.upload(file, MinioConfig.BucketName,fileName, UploadType.上传Minio);
  34. log.info(url);
  35. String originalFilename = file.getOriginalFilename();
  36. FileEntity fileEntity = FileEntity.builder()
  37. .fileId(UUID.randomUUID().toString())
  38. .fileName(url.substring(url.lastIndexOf("/")+1))
  39. .fileType("1")
  40. .ext(originalFilename.substring(originalFilename.lastIndexOf(".")+1))
  41. .storageName(originalFilename.substring(0,originalFilename.lastIndexOf(".")))
  42. .fileSize((double)file.getSize())
  43. .url(url)
  44. .uri(fileName)
  45. .insertDatetime(new Date())
  46. .lastUpdateTime(new Date())
  47. .build();
  48. System.out.println(fileEntity);
  49. fileMapper.insert(fileEntity);
  50. return JSONObject.toJSONString(fileEntity);
  51. }
  52. }
  53. }