Commit 070d06a0 by baiyh

初始化

parents
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### IntelliJ IDEA ###
.idea/modules.xml
.idea/jarRepositories.xml
.idea/compiler.xml
.idea/libraries/
*.iws
*.iml
*.ipr
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store
\ No newline at end of file
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="file://$PROJECT_DIR$/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/src/main/resources" charset="UTF-8" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GitToolBoxBlameSettings">
<option name="version" value="2" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="MavenProjectsManager">
<option name="originalFiles">
<list>
<option value="$PROJECT_DIR$/pom.xml" />
</list>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" default="true" project-jdk-name="corretto-1.8" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>
\ No newline at end of file
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.makeit</groupId>
<artifactId>ssoUpload</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- Spring Boot版本(兼容Java 8) -->
<spring-boot.version>2.7.18</spring-boot.version>
</properties>
<!-- 引入Spring Boot父依赖,简化配置 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.18</version>
<relativePath/>
</parent>
<dependencies>
<!-- Spring Web核心依赖(提供HTTP服务和文件上传支持) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 文件处理工具类(简化IO操作) -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.14.0</version>
</dependency>
<!-- Lombok(简化实体类代码,减少getter/setter) -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- Spring Boot测试依赖(可选,用于单元测试) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<!-- Spring Boot打包插件(可将项目打包为可执行JAR) -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot.version}</version>
<configuration>
<!-- 解决Lombok打包问题 -->
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file
package com.makeit;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* SSO文件上传服务启动类
* 负责启动Spring Boot应用,扫描并加载所有组件(Controller、Service等)
*/
@SpringBootApplication
public class SsoUploadApplication {
public static void main(String[] args) {
// 启动Spring Boot应用,参数args用于接收外部启动参数(如环境切换:--spring.profiles.active=prod)
SpringApplication.run(SsoUploadApplication.class, args);
System.out.println("SSO文件上传服务启动成功!访问地址:http://localhost:端口号(测试4399/生产8080)");
}
}
\ No newline at end of file
package com.makeit.common;
import lombok.Data;
/**
* 统一API返回结果类
*/
@Data
public class Result<T> {
// 状态码:200=成功,500=错误
private int code;
// 提示信息
private String msg;
// 数据(成功时返回文件URL,失败时为null)
private T data;
// 成功返回(带自定义提示)
public static <T> Result<T> success(String msg, T data) {
Result<T> result = new Result<>();
result.setCode(200);
result.setMsg(msg);
result.setData(data);
return result;
}
// 成功返回(默认提示)
public static <T> Result<T> success(T data) {
return success("操作成功", data);
}
// 错误返回
public static <T> Result<T> error(String msg) {
Result<T> result = new Result<>();
result.setCode(500);
result.setMsg(msg);
result.setData(null);
return result;
}
}
\ No newline at end of file
package com.makeit.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class CorsConfig {
@Bean
public CorsFilter corsFilter() {
// 1. 创建 CORS 配置对象
CorsConfiguration config = new CorsConfiguration();
// 允许的前端域名(替换为你的前端实际域名,如 http://localhost:8081、http://192.168.168.18:8080)
// 开发环境可临时用 "*" 允许所有域名(生产环境不推荐,需指定具体域名)
config.addAllowedOrigin("http://localhost:8080");
config.addAllowedOrigin("http://10.121.24.151:8080");
config.addAllowedOrigin("http://10.121.22.151:8080");
// 允许的请求方法(GET、POST、OPTIONS 等,预检请求需要允许 OPTIONS)
config.addAllowedMethod("*");
// 允许的请求头(如 Content-Type、Authorization 等)
config.addAllowedHeader("*");
// 允许前端携带 Cookie(若不需要,可设为 false)
config.setAllowCredentials(true);
// 预检请求的有效期(秒),避免频繁发送 OPTIONS 请求
config.setMaxAge(3600L);
// 2. 配置 CORS 规则生效的路径(/** 表示所有接口)
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
// 3. 返回 CORS 过滤器
return new CorsFilter(source);
}
}
\ No newline at end of file
package com.makeit.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* 静态资源映射配置:让前端能通过URL访问本地存储的文件
*/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Value("${file.upload.local-path}")
private String localUploadPath;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// 映射规则:访问 http://localhost:8080/file/** 时,指向本地存储目录
registry.addResourceHandler("/file/**")
.addResourceLocations("file:" + localUploadPath + "/");
}
}
\ No newline at end of file
package com.makeit.controller;
import com.makeit.common.Result;
import com.makeit.utils.FileUploadUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
/**
* 文件上传控制器
*/
@Slf4j
@RestController
@RequestMapping("/api/upload")
public class FileUploadController {
@Autowired
private FileUploadUtil fileUploadUtil;
/**
* 单文件上传接口
* @param file 前端上传的文件(form-data格式,参数名必须为file)
* @return 上传结果(成功返回服务器访问路径,失败返回错误信息)
*/
@PostMapping("/file")
public Result<String> uploadFile(@RequestParam("file") MultipartFile file) {
try {
// 调用工具类上传文件,获取服务器路径
String fileUrl = fileUploadUtil.uploadFile(file);
return Result.success("上传成功", fileUrl);
} catch (Exception e) {
log.error("文件上传失败", e);
return Result.error("上传失败:" + e.getMessage());
}
}
}
\ No newline at end of file
package com.makeit.controller;
import com.makeit.common.Result;
import com.makeit.exception.FileTypeNotAllowedException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
@RestControllerAdvice
public class GlobalExceptionHandler {
@Value("${spring.servlet.multipart.max-file-size}")
private String maxFileSize;
@Value("${spring.servlet.multipart.max-request-size}")
private String maxRequestSize;
// 处理文件大小超限异常(原有)
@ExceptionHandler(MaxUploadSizeExceededException.class)
public Result<String> handleMaxUploadSizeException(MaxUploadSizeExceededException e) {
String message = e.getMessage().contains("max-file-size")
? "单个文件大小不能超过" + maxFileSize + "!"
: "单次上传总大小不能超过" + maxRequestSize + "!";
return Result.error(message);
}
// 处理文件类型不允许的异常(新增)
@ExceptionHandler(FileTypeNotAllowedException.class)
public Result<String> handleFileTypeNotAllowedException(FileTypeNotAllowedException e) {
// 直接返回自定义异常中的错误信息
return Result.error(e.getMessage());
}
// 处理其他未知异常(原有)
@ExceptionHandler(Exception.class)
public Result<String> handleOtherException(Exception e) {
return Result.error("文件上传失败:" + e.getMessage());
}
}
\ No newline at end of file
package com.makeit.exception;
/**
* 自定义异常:文件类型不允许
*/
public class FileTypeNotAllowedException extends RuntimeException {
// 构造方法,接收错误信息
public FileTypeNotAllowedException(String message) {
super(message);
}
}
\ No newline at end of file
package com.makeit.utils;
import com.makeit.exception.FileTypeNotAllowedException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;
@Slf4j
@Component
public class FileUploadUtil {
@Value("${file.upload.local-path}")
private String localUploadPath;
@Value("${file.upload.base-url}")
private String baseUrl;
// 从配置文件读取允许的文件类型列表(如["image/jpeg", "video/mp4"])
@Value("#{T(java.util.Arrays).asList('${file.upload.allow-types:}')}")
private List<String> allowTypes;
public String uploadFile(MultipartFile file) throws IOException {
// 1. 校验文件是否为空
if (file.isEmpty()) {
throw new RuntimeException("上传文件不能为空");
}
// 2. 校验文件类型(核心逻辑)
String fileContentType = file.getContentType(); // 获取文件MIME类型(如"video/mp4")
// 如果MIME类型不在允许列表中,抛出自定义异常
if (!allowTypes.contains(fileContentType)) {
throw new FileTypeNotAllowedException(
"文件类型不允许!允许的类型:" + allowTypes + ",当前文件类型:" + fileContentType
);
}
// 3. 按日期创建目录(原有逻辑)
String dateDir = new SimpleDateFormat("yyyyMMdd").format(new Date());
File uploadDir = new File(localUploadPath + File.separator + dateDir);
if (!uploadDir.exists() && !uploadDir.mkdirs()) {
throw new RuntimeException("创建存储目录失败:" + uploadDir.getAbsolutePath());
}
// 4. 生成唯一文件名并保存(原有逻辑)
String originalFileName = file.getOriginalFilename();
String fileExt = FilenameUtils.getExtension(originalFileName);
String uniqueFileName = UUID.randomUUID().toString() + "." + fileExt;
File destFile = new File(uploadDir, uniqueFileName);
file.transferTo(destFile);
log.info("文件上传成功,本地路径:{}", destFile.getAbsolutePath());
// 5. 返回访问URL
return baseUrl + dateDir + "/" + uniqueFileName;
}
}
\ No newline at end of file
# 测试环境配置
spring:
application:
name: ssoUpload-service-prod # 生产环境应用名(区分生产)
# 测试环境服务器配置
server:
port: 4399 # 测试端口
servlet:
context-path: / # 无上下文前缀
tomcat:
max-http-form-post-size: 500MB
connection-timeout: 60000ms
# 测试环境文件存储配置(本地/开发服务器路径)
file:
upload:
local-path: /home/ssoUpload # 测试环境存储路径(建议独立于生产)
base-url: http://10.121.22.151:8080/ssoUpload/ # 测试环境访问URL(本地或测试服务器IP)
allow-types: image/jpeg,image/png,audio/mpeg,audio/wav,video/mp4,video/x-flv
# 测试环境日志配置
logging:
level:
root: INFO
com.makeit: DEBUG # 测试环境日志级别可略低,便于调试
file:
name: /home/ssoUpload/ssoUpload-test.log # 测试日志路径
\ No newline at end of file
# 测试环境配置
spring:
application:
name: ssoUpload-service-test # 测试环境应用名(区分生产)
# 测试环境服务器配置
server:
port: 4399 # 测试端口
servlet:
context-path: / # 无上下文前缀
tomcat:
max-http-form-post-size: 500MB
connection-timeout: 60000ms
# 测试环境文件存储配置(本地/开发服务器路径)
file:
upload:
local-path: /Users/baiyh/Desktop/test # 测试环境存储路径(建议独立于生产)
base-url: http://localhost:4399 # 测试环境访问URL(本地或测试服务器IP)
allow-types: image/jpeg,image/png,audio/mpeg,audio/wav,video/mp4,video/x-flv
# 测试环境日志配置
logging:
level:
root: INFO
com.makeit: DEBUG # 测试环境日志级别可略低,便于调试
file:
name: /Users/baiyh/Desktop/test/ssoUpload-test.log # 测试日志路径
\ No newline at end of file
# 主配置文件:合并所有spring节点,修复语法冲突,保留公共配置
spring:
# 1. 环境激活配置
profiles:
active: prod # 默认激活测试环境,生产启动参数:--spring.profiles.active=prod
# 2. 文件上传公共配置(合并到spring节点下,避免重复定义)
servlet:
multipart:
enabled: true
max-file-size: 1000MB
max-request-size: 500MB
# file-size-threshold: 10MB
# location: /home/temp # 临时文件存储路径(所有环境共享,若需环境差异化可移到对应环境配置)
# 公共服务器配置(编码已归到spring,此处保留其他共享项)
server:
servlet:
encoding:
enabled: true
charset: UTF-8
force: true
# 日志格式(所有环境共享)
logging:
pattern:
console: "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{50} - %msg%n"
file: "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{50} - %msg%n"
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment