about 5 years ago
Springboot 中的檔案上傳可以配置一個 檔案最大值,這個是全域共用的,所以當檔案大於這個最大值時,還沒進入 Controller 就被拒絕了,顯示的訊息是 Spring 預設的英文訊息......
所以
腦殘PM 就說這是 bug
就說要改底層的顯示訊息為中文的.....
無言....什麼都要處理成中文,不然你自己來做個 springcn 吧
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import org.apache.tomcat.util.http.fileupload.FileUploadBase;
import org.springframework.core.env.Environment;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
@Data
public class CustomExceptionHandlerExceptionResolver extends ExceptionHandlerExceptionResolver {
private Environment environment;
protected ModelAndView doResolveHandlerMethodException(HttpServletRequest request, HttpServletResponse response, HandlerMethod handlerMethod, Exception exception) {
ModelAndView modelAndView = new ModelAndView();
if(exception instanceof MultipartException){
if(((MultipartException) exception).getRootCause() instanceof FileUploadBase.FileSizeLimitExceededException){
Map<String, Object> errorAttributes = new LinkedHashMap<String, Object>();
errorAttributes.put("timestamp", new Date());
errorAttributes.put("status", 400);
errorAttributes.put("error", "Validation failed");
errorAttributes.put("exception", exception.getClass());
errorAttributes.put("message", "系统限制档案不得超过 " + environment.getProperty("spring.http.multipart.max-file-size"));
errorAttributes.put("path", request.getRequestURI());
ObjectMapper objectMapper = new ObjectMapper();
try {
response.setStatus(400);
ServletOutputStream sos = response.getOutputStream();
sos.write(objectMapper.writeValueAsBytes(errorAttributes));
sos.flush();
sos.close();
} catch (IOException e) {
e.printStackTrace();
}
}else{
modelAndView = super.doResolveHandlerMethodException(request,response,handlerMethod,exception);
}
}else{
modelAndView = super.doResolveHandlerMethodException(request,response,handlerMethod,exception);
}
return modelAndView;
}
}
@Slf4j
@Configuration
public class ActivityConfig {
@Autowired
private Environment environment;
@Bean
public ExceptionHandlerExceptionResolver getHandlerExceptionResolver() {
CustomExceptionHandlerExceptionResolver customExceptionHandlerExceptionResolver = new CustomExceptionHandlerExceptionResolver();
customExceptionHandlerExceptionResolver.setEnvironment(environment);
return customExceptionHandlerExceptionResolver;
}
}
就這樣覆蓋預設處理,但是說實在的盡量不要這樣搞,怕你 Springboot 2 升級會很痛苦
直接不限制最簡單(程式內另有檢核所以影響不大)
http:
multipart:
max-file-size: -1
max-request-size: -1