两种方式上传,一种是Minio文件服务器,一种是Nginx下静态资源服务器(未完)
架构层次
yml
server:
port: 8082
spring:
servlet:
multipart:
max-file-size: 500MB
max-request-size: 500MB
## Mysql
# datasource:
# url: jdbc:mysql://192.168.10.223:3306/sjtc_bz_db?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF8&zeroDateTimeBehavior=convertToNull
# username: root
# password: dca282e70e
# driver-class-name: com.mysql.jdbc.Driver
# Oracle
datasource:
url: jdbc:oracle:thin:@192.168.10.223:1522/ORCLPDB1
username: SJTC_BZ_DB
password: 123456
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: oracle.jdbc.OracleDriver
pom
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<springfox.version>2.7.0</springfox.version>
<mysql.version>5.1.40</mysql.version>
<mybatisplus.version>2.1.0</mybatisplus.version>
<mybatisplus-spring-boot-starter.version>1.0.4</mybatisplus-spring-boot-starter.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>8.2.2</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${springfox.version}</version>
<exclusions>
<exclusion>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
</exclusion>
</exclusions>
</dependency>
<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>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!-- mybatis-plus begin -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatisplus-spring-boot-starter</artifactId>
<version>${mybatisplus-spring-boot-starter.version}</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>${mybatisplus.version}</version>
</dependency>
<dependency>
<groupId>com.oracle.ojdbc</groupId>
<artifactId>ojdbc8</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.9</version>
</dependency>
<!-- druid 连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
config
MinioConfig
public class MinioConfig {
/**
* ip+port
*/
public static String Url = "http://192.168.10.223:9002";
public static String AccessKey = "orisdom";
public static String SecretKey = "orisdom123";
public static String BucketName = "sjtc";
}
SimpleConfig
public class SimpleConfig {
/**
* 本地文件保存根路径
*/
/**
* ip+port
*/
public static String Url = "";
public static String localPath = "";
}
enums
FileType
public enum FileType {
文本("0"),图片("1"),视频("2");
private final String type;
FileType(String type){
this.type = type;
}
public String getType() {
return type;
}
}
UploadType
public enum UploadType {
上传本地("normal"),上传Minio("minio");
private final String type;
UploadType(String type){
this.type = type;
}
public String getType() {
return type;
}
}
entity
FileEntity
/**
* @author: Jili
* @description: com.orisdom.modules.common.entity
* @date: Created on 2021/9/1 10:33
*/
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Data
@ApiModel(description = "文件上传")
@TableName("C_FILES")
public class FileEntity implements Serializable{
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "文件ID")
@TableId(value = "FILE_ID", type = IdType.UUID)
private String fileId;
@ApiModelProperty(value = "文件名称")
@TableField("FILE_NAME")
private String fileName;
@ApiModelProperty(value = "类型")
@TableField("FILE_TYPE")
private String fileType;
@ApiModelProperty(value = "拓展名")
@TableField("EXT")
private String ext;
@ApiModelProperty(value = "文件在磁盘中的存储名称,不包含路径和扩展名")
@TableField("STORAGE_NAME")
private String storageName;
@ApiModelProperty(value = "文件大小")
@TableField("FILE_SIZE")
private Double fileSize;
@TableField("URI")
private String uri;
@TableField("URL")
private String url;
@TableField("INSERT_USER")
private String insertUser;
@TableField("LAST_UPDATE_USER")
private String lastUpdateUser;
@TableField("INSERT_DATETIME")
private Date insertDatetime;
@TableField("LAST_UPDATE_TIME")
private Date lastUpdateTime;
}
service
IFileService
public interface IFileService {
/**
* @return
*/
// String upload(MultipartFile file, FileType fileType, UploadType uploadType);
/**
* MultipartFile
* @param file 上传文件
* @param bucketName 桶名
* @param fileName 文件保存新名字
* @param uploadType 上传方式
* @return
*/
String upload(MultipartFile file, String bucketName, String fileName,UploadType uploadType);
/**
* File
* @param file 上传文件
* @param fileType 文件类型
* @param uploadType 上传方式
* @return
*/
String upload(File file, FileType fileType, UploadType uploadType) throws Exception;
}
FileService
@Service
public class FileService implements IFileService {
// @Override
// public String upload(MultipartFile file, FileType fileType, UploadType uploadType) {
// String url = null;
// switch (uploadType) {
// case 上传本地:
// url = SimpleFileUtil.getInstance().upload(file, fileType);
// break;
// case 上传Minio:
// url = MinioFileUtil.getInstance().upload(MinioConfig.BucketName, file);
// break;
// default:
// break;
// }
// return url;
// }
/*
改良版
*/
@Override
public String upload(MultipartFile file, String bucketName, String fileName,UploadType uploadType) {
String url = null;
switch (uploadType) {
case 上传本地:
url = SimpleFileUtil.getInstance().upload(file, fileName);
break;
case 上传Minio:
url = MinioFileUtil.getInstance().upload(file,bucketName,fileName);
break;
default:
break;
}
return url;
}
@Override
public String upload(File file, FileType fileType, UploadType uploadType) throws Exception {
FileInputStream inputStream = new FileInputStream(file);
String url = null;
switch (uploadType) {
case 上传本地:
url = SimpleFileUtil.getInstance().upload(inputStream, file.getName(), fileType);
break;
case 上传Minio:
url = MinioFileUtil.getInstance().upload(fileType.getType(), file.getName(), inputStream);
break;
default:
break;
}
return url;
}
}
util
MinioFileUtil
@Service
public class FileService implements IFileService {
// @Override
// public String upload(MultipartFile file, FileType fileType, UploadType uploadType) {
// String url = null;
// switch (uploadType) {
// case 上传本地:
// url = SimpleFileUtil.getInstance().upload(file, fileType);
// break;
// case 上传Minio:
// url = MinioFileUtil.getInstance().upload(MinioConfig.BucketName, file);
// break;
// default:
// break;
// }
// return url;
// }
/*
改良版
*/
@Override
public String upload(MultipartFile file, String bucketName, String fileName,UploadType uploadType) {
String url = null;
switch (uploadType) {
case 上传本地:
url = SimpleFileUtil.getInstance().upload(file, fileName);
break;
case 上传Minio:
url = MinioFileUtil.getInstance().upload(file,bucketName,fileName);
break;
default:
break;
}
return url;
}
@Override
public String upload(File file, FileType fileType, UploadType uploadType) throws Exception {
FileInputStream inputStream = new FileInputStream(file);
String url = null;
switch (uploadType) {
case 上传本地:
url = SimpleFileUtil.getInstance().upload(inputStream, file.getName(), fileType);
break;
case 上传Minio:
url = MinioFileUtil.getInstance().upload(fileType.getType(), file.getName(), inputStream);
break;
default:
break;
}
return url;
}
}
更多可以参考 https://blog.csdn.net/hzw2312/article/details/106078390
SimpleFileUtil
public class SimpleFileUtil {
private static SimpleFileUtil instance = new SimpleFileUtil();
private SimpleFileUtil(){};
public static SimpleFileUtil getInstance() {
return instance;
}
/**
* 上传文件
* @param multipartFile 文件
* @param fileFullName 文件相对路径 如:/images/demo.jpg
* @return
*/
@SneakyThrows(Exception.class)
public String upload(MultipartFile multipartFile, String fileFullName){
// String dirPath;
// DateFormatter formatter = new DateFormatter();
// formatter.setPattern("yyyyMMdd");
// String dateSuffix = formatter.print(new Date(), Locale.CHINESE);
// dirPath = SimpleConfig.localPath+"/"+type.getType()+"/"+dateSuffix;
// String originalFilename = multipartFile.getOriginalFilename();
// String fileName = type.getType() + "_" +
// System.currentTimeMillis() +
// originalFilename.substring(originalFilename.lastIndexOf("."));
// Path path = Paths.get(dirPath,fileName);
// Set<PosixFilePermission> permissions = PosixFilePermissions.fromString("r-xr-----");
// FileAttribute<Set<PosixFilePermission>> fileAttributes = PosixFilePermissions.asFileAttribute(permissions);
String dirPath = fileFullName.substring(0,fileFullName.lastIndexOf("/"));
String fileName = fileFullName.substring(fileFullName.lastIndexOf("/")+1);
Path path = Paths.get(dirPath,fileName);
boolean dirExist = Files.exists(Paths.get(dirPath));
if (!dirExist){
Files.createDirectories(Paths.get(dirPath));
}
boolean fileExist = Files.exists(path);
if (!fileExist) {
Files.createFile(path);
}
Files.copy(multipartFile.getInputStream(),path, StandardCopyOption.REPLACE_EXISTING);
return SimpleConfig.Url+fileFullName;
}
/**
* 上传文件
* @param inputStream 文件输入流
* @param oriFileName 文件名称
* @param type 文件类型
* @return
*/
@SneakyThrows(Exception.class)
public String upload(InputStream inputStream,String oriFileName, FileType type){
String dirPath;
DateFormatter formatter = new DateFormatter();
formatter.setPattern("yyyyMMdd");
String dateSuffix = formatter.print(new Date(), Locale.CHINESE);
dirPath = SimpleConfig.localPath+"/"+type.getType()+"/"+dateSuffix;
String fileName = type.getType() + "_" +
System.currentTimeMillis() +
oriFileName.substring(oriFileName.lastIndexOf("."));
Path path = Paths.get(dirPath,fileName);
// Set<PosixFilePermission> permissions = PosixFilePermissions.fromString("r-xr-----");
// FileAttribute<Set<PosixFilePermission>> fileAttributes = PosixFilePermissions.asFileAttribute(permissions);
boolean dirExist = Files.exists(Paths.get(dirPath));
if (!dirExist){
Files.createDirectories(Paths.get(dirPath));
}
boolean fileExist = Files.exists(path);
if (!fileExist) {
Files.createFile(path);
}
Files.copy(inputStream,path, StandardCopyOption.REPLACE_EXISTING);
return this.getFilePath(type, path.toString());
}
/**
* 获取相对路径
*
* @param absolutePath
* @return
*/
private String getFilePath(FileType type, String absolutePath) {
absolutePath = absolutePath.replace("\\", "/");
int imagePathLength = SimpleConfig.localPath.length();
String path;
if (absolutePath.length() > imagePathLength) {
path = absolutePath.substring(imagePathLength + 1, absolutePath.length());
} else {
path = absolutePath.substring(imagePathLength, absolutePath.length());
}
return path;
}
}
mapper
FileMapper
public interface FileMapper extends BaseMapper<FileEntity> {
}
Demo 接口测试
controller
@RestController
public class FileController {
@Autowired
IFileService fileService;
@Autowired
FileMapper fileMapper;
private static final Logger log = LoggerFactory.getLogger(FileController.class);
@PostMapping("/test")
@ApiOperation(value = "文件上传", response = String.class)
public void test(@RequestParam("file") MultipartFile file, HttpServletRequest req) {
if (file.isEmpty()) {
// return "请选择文件!";
} else {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String date = sdf.format(new Date());
String path="/"+date+"/"+UUID.randomUUID().toString().replace("-","")+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
SimpleConfig.Url="116.62.41.96:8081";
SimpleConfig.localPath="/images";
String fileName = SimpleConfig.Url+SimpleConfig.localPath+path;
String url =fileService.upload(file,"",path,UploadType.上传本地);
System.out.println(url);
}
}
@PostMapping("/upload")
@ApiOperation(value = "文件上传", response = String.class)
public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest req) {
if (file.isEmpty()) {
return "请选择文件!";
} else {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String date = sdf.format(new Date());
String fileName=date+"/"+UUID.randomUUID().toString().replace("-","")+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
String url=fileService.upload(file, MinioConfig.BucketName,fileName, UploadType.上传Minio);
log.info(url);
String originalFilename = file.getOriginalFilename();
FileEntity fileEntity = FileEntity.builder()
.fileId(UUID.randomUUID().toString())
.fileName(url.substring(url.lastIndexOf("/")+1))
.fileType("1")
.ext(originalFilename.substring(originalFilename.lastIndexOf(".")+1))
.storageName(originalFilename.substring(0,originalFilename.lastIndexOf(".")))
.fileSize((double)file.getSize())
.url(url)
.uri(fileName)
.insertDatetime(new Date())
.lastUpdateTime(new Date())
.build();
System.out.println(fileEntity);
fileMapper.insert(fileEntity);
return JSONObject.toJSONString(fileEntity);
}
}
}