Springboot报错Failed to parse multipart servlet request; nested exception is java.lang.IllegalStateE

今天我在开发Springboot上传功能时报错:Failed to parse multipart servlet request; nested exception is java.lang.IllegalStateException: The multi-part request contained parameter data (excluding uploaded files) that exceeded the maximum allowed limit。下面我来分享一下我是如何解决这个问题的。

首先,我修改了application.properties。在其中添加下列配置:

spring.servlet.multipart.max-file-size = 50MB
spring.servlet.multipart.max-request-size = 50MB

这里的值可以根据实际需求调整,以50MB为例。这样,我们就设置了最大允许上传的文件大小为50MB,并限制了最大请求大小也为50MB。

然后,在我们的Controller中,我们还需要修改我们的请求映射函数,将其改为如下形式:

@PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<String> upload(@RequestParam("file") MultipartFile file) {
    // 处理上传文件的逻辑
}

注意,这里需要指明content type为multipart/form-data,否则会出现报错。

如果还是出现报错,我们可以尝试将上传限制在单个请求中,将文件分块上传并处理,避免一次性上传大文件出现的问题。这里给出一个实现的例子:

@PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<String> upload(@RequestParam("file") MultipartFile file) throws IOException {
    // 设置缓冲区大小为100KB
    int bufferSize = 102400;
    byte[] buffer = new byte[bufferSize];
    InputStream inputStream = file.getInputStream();
    while (true) {
        int bytesRead = inputStream.read(buffer, 0, bufferSize);
        if (bytesRead <= 0) {
            break;
        }
        // 处理上传文件的逻辑
    }
    inputStream.close();
    return ResponseEntity.ok("Upload successful");
}

以上就是解决Failed to parse multipart servlet request报错的方法。

除了以上提到的方法之外,我们还可以尝试在Springboot中使用 @ControllerAdvice 和 @ExceptionHandler 来捕获和处理上传文件时出现的异常。

首先,我们需要在 ControllerAdvice 中定义异常处理方法:

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public ResponseEntity<String> handleMaxUploadSizeExceededException(MaxUploadSizeExceededException e) {
        return ResponseEntity.status(HttpStatus.PAYLOAD_TOO_LARGE).body("File size exceeds the limit");
    }

    // 其他异常处理方法
    // ...
}

这里我们定义了一个 MaxUploadSizeExceededException 的异常处理方法,表示当上传文件大小超过了限制时,我们将返回 PAYLOAD_TOO_LARGE 状态码并返回 “File size exceeds the limit” 的错误信息。

然后,在我们的 Controller 中,我们就可以使用该异常处理方法了:

@PostMapping("/upload")
public ResponseEntity<String> upload(@RequestParam("file") MultipartFile file) {
    try {
        // 处理上传文件的逻辑
    } catch (MaxUploadSizeExceededException e) {
        throw e;
    } catch (Exception e) {
        // 其他异常处理
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Internal server error");
    }
    return ResponseEntity.ok("Upload successful");
}

注意,我们需要在 catch 语句中捕获 MaxUploadSizeExceededException 异常,并使用 throw 语句将其抛出供 ControllerAdvice 处理。同时,我们还需要捕获其他可能出现的异常,并进行相应的处理。

以上就是我分享的关于解决 Springboot 上传文件时出现的 Failed to parse multipart servlet request 报错的方法,希望对大家有所帮助!

猜你喜欢

转载自blog.csdn.net/javamendou/article/details/131361702