修复:调整后端上传大小限制

This commit is contained in:
xiaowang
2026-03-26 11:17:30 +08:00
parent 22e28a9f48
commit 0959f14555
3 changed files with 78 additions and 0 deletions
@@ -2,6 +2,8 @@ package com.xiaowang.yuminailcore.common;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
@@ -19,6 +21,8 @@ import javax.validation.ConstraintViolationException;
@RestControllerAdvice
public class GlobalExceptionHandler {
private static final long MAX_UPLOAD_SIZE_BYTES = 5L * 1024 * 1024;
@ExceptionHandler(MethodArgumentNotValidException.class)
public Result<Void> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
String message = e.getBindingResult().getAllErrors().stream()
@@ -46,6 +50,28 @@ public class GlobalExceptionHandler {
return Result.error(message);
}
@ExceptionHandler(MaxUploadSizeExceededException.class)
public Result<Void> handleMaxUploadSizeExceededException(MaxUploadSizeExceededException e) {
log.warn("上传文件超过限制: {}", e.getMessage());
return Result.error(buildUploadLimitMessage());
}
@ExceptionHandler(MultipartException.class)
public Result<Void> handleMultipartException(MultipartException e) {
log.warn("文件上传请求异常: {}", e.getMessage());
return Result.error(buildUploadLimitMessage());
}
@ExceptionHandler(IllegalStateException.class)
public Result<Void> handleIllegalStateException(IllegalStateException e) {
if (isUploadLimitException(e)) {
log.warn("上传文件超过限制: {}", e.getMessage());
return Result.error(buildUploadLimitMessage());
}
log.error("非法状态异常: ", e);
return Result.error(e.getMessage());
}
/**
* 处理运行时异常
*/
@@ -63,4 +89,22 @@ public class GlobalExceptionHandler {
log.error("系统异常: ", e);
return Result.error("系统繁忙,请稍后再试");
}
private String buildUploadLimitMessage() {
return "上传文件不能超过 " + (MAX_UPLOAD_SIZE_BYTES / 1024 / 1024) + "MB";
}
private boolean isUploadLimitException(Throwable throwable) {
Throwable current = throwable;
while (current != null) {
String message = current.getMessage();
if (message != null && (message.contains("maximum permitted size")
|| message.contains("FileSizeLimitExceededException")
|| message.contains("exceeds its maximum permitted size"))) {
return true;
}
current = current.getCause();
}
return false;
}
}
@@ -1,6 +1,10 @@
spring:
datasource:
url: jdbc:mysql://localhost:3306/yumi_nail?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
servlet:
multipart:
max-file-size: 5MB
max-request-size: 10MB
jackson:
time-zone: Asia/Shanghai
date-format: yyyy-MM-dd HH:mm:ss