SpringMVC file upload: trouble with MultipartException

gossip

I write this note and bring you a passage, excerpted from a certain big shot (I can’t remember who it is hahaha):

The hardest bugs to find are often the lowest level errors.

This passage always benefited me a lot during the learning stage when I was troubleshooting and analyzing the cause of the problem.

text

Preface

Personal project development needs to complete a function of uploading, deleting and downloading files . This should be a simple thing, but it has hindered me for a long time and made the progress of my project slow. Of course, it's because there have been a lot of things lately, but external things are no excuse. . Okay, enough chatter, let’s post some questions first.

question

Problem 1: The requested file size exceeds the default limit

The first is the issue of file size. MaxUploadSizeException occurred in the springboot project . Springboot's default upload file size limit is 1MB, and the default single request size limit is 10MB . If the size is exceeded, the above exception will be thrown. The exceptions when the requested file size exceeds 1MB and exceeds 10MB are different:

Exception information when exceeding 1MB

Resolved [org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size exceeded; nested exception is java.lang.IllegalStateException: org.apache.tomcat.util.http.fileupload.FileUploadBase$FileSizeLimitExceededException: The field file exceeds its maximum permitted size of 1048576 bytes.]

Exception information when exceeding 10MB

Resolved [org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size exceeded; nested exception is java.lang.IllegalStateException: org.apache.tomcat.util.http.fileupload.FileUploadBase$SizeLimitExceededException: the request was rejected because its size (12209424) exceeds the configured maximum (10485760)]

When the file exceeds 10MB, the project reports an error, but this exception cannot be caught by the custom global exception handler @ControllerAdvice, and the page directly reports 500

reason

Excerpted from: http://t.csdn.cn/cRQOQ

The following figure is the single request response process of SpringMVC

This picture explains why we cannot catch exceptions in Controller. It's because MultipartException was caught and thrown (and had a return value) in the first two stages, and did not reach the Controller layer. This is also the reason why we set up a global capture, which can capture MultipartException exceptions but cannot correctly return the object to the front end (the return value is processed in advance).

solve

There are two solutions shown in the excerpted article from the big guy. I used the simplest and most convenient one:

Configure the request size limit and upload file size limit in the project's configuration file application.yml , as well as the maximum throughput of tomcat

spring:
    servlet:
        multipart:
          max-file-size: 5MB
          max-request-size: 20MB

server:
  port: 8999
  tomcat:
    # 当文件超过tomcat的大小限制后会先于Controller触发异常,此时我们的异常处理器无法捕获异常
    max-swallow-size: 30MB # 内嵌tomcat的最大吞吐量,设置 -1 不限制

Problem 2: The upload file interface and request do not follow the necessary conditions

The second problem occurs in the joint debugging of the front-end and back-end interfaces for uploading files. The following is the exception information:

org.springframework.web.multipart.MultipartException: The current request is not a multipart request

reason

The reasons and solutions for the most likely mistakes are summarized in my study as follows:

1. The request method must be post

2. The requested contentType must be set to start with "multipart/"

3. The receiving parameters of the backend interface need to use @RequestParam to specify the key of the form, which is used to receive file data.

solve

The main points are as follows

Front-end code:

 Pay attention to this third picture! !

Backend interface

@RestController
@RequestMapping("/file")
@Slf4j
public class FileWorkerController {


    @PostMapping("upload")
    @ResponseBody
    ResultVO<String> uploadAndSaveForImage(@RequestParam("file") MultipartFile file) {
        log.info("multipart ==> {}", file);
        return ResultVO.ok();
    }
}

 Learn from the big guy’s article: http://t.csdn.cn/LYbHF

I would like to express my great gratitude to this junior!

personal problem

So where is my mental weakness? In fact, in the front-end code, I encapsulated the FormData object and passed the file file. . . Speechless. .

Afterword

Therefore, details determine success or failure, and the most difficult bugs to find may appear in the lowest-level operations. When you find that you have searched all the information and found that the main problems are not solved, it is time to find your own problems. Of course, you can also pay attention to see if it is your own problem from the beginning. Here I also take this opportunity to remind myself, stay humble, and move forward! !

If you have other opinions and views, please leave them in the comment area! If you have any other intentions for cooperation or exchange, please feel free to message me privately!

Guess you like

Origin blog.csdn.net/Ccc67ol/article/details/132371463