Null check for multipart file

In Spring Boot 2.1.* MultipartFile always gets filled even if it isn't required so the most reliable way to check whether an optional file was sent I've found is

if(file.getSize() > 0)
    //file has data

for a requestparameter defined as

@RequestParam(value = "file", required = false) MultipartFile file

Just for the sake of you to accept an answer and this question doesn't stay as "unanswered", I'll post my comment as an answer:

You can call

if (projectImg != null) { ... }

before or instead

if (projectImg.isEmpty()) { ... }

The best way to check if the file is null or not is using the MultipartFile isEmpty() method in the following way.

if(!chartImg.isEmpty()){
 // your logic here 
}else{
 // your logic here 
}


if(!projectImg.isEmpty()){
// your logic here 
}else{
 // your logic here 
}

if(projectImg != null){ } does not always work

Tags:

Java