MissingServletRequestPartException - Required request part 'file' is not present error on file-upload process

26 views Asked by At

I am writing a gateway for our ui with Kotlin (version: 1.4.31) and Spring (version: 2.6.6). A new request came with the need to upload a file and I started writing the relevant endpoint.

I used MultipartFile property for this need. Our code is like that;

@PostMapping("/upload-file", consumes = [MediaType.MULTIPART_FORM_DATA_VALUE])
fun uploadFile(
    @RequestParam(value = "file", required = true) file: MultipartFile
): ResponseEntity<FileUploadResponse> {
    return ResponseEntity.ok(service.uploadFile(file = file))
}

When finishing this code and tested it, I realized that this request throws MissingServletRequestPartException - Required request part 'file' is not present error on file-upload process error.

I tried the solutions suggested on the internet regarding this error, but I did not get any results.

I also tried this code block in another project that is similar versions of Kotlin and Spring with my failed project and in there code block was running!

So, there is only one difference between failed and success project. Our failed project wraps request object for logging and vs. And file that I uploaded was missing because of that.

When I deeped dive with request object, I found that in there there is a property that named 'parts' in request and in my failed project, this property did not fill with files I uploaded. In spring MVC there is code like that;

protected final void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.processRequest(request, response);
    }

So I debugged this code and I realized that, if I called parts with debug evatualate, it filled but if I not it did not fill. So I wrote a line that only called request.parts with like that and it worked!

if (isFileUpload) { //if it is a file upload related endpoint
    request.parts // only call request.parts, not setting any variable and using.
}

I think that this property filling needs lazy loading and it is not working if it is not read.

My question here is, is there any other solution other than the solution I wrote? Thanks in advance for the answers...

0

There are 0 answers