Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null check for multipart file

Tags:

java

I'm processing two different multipart files in my Spring controller.

Both files are then sent on to a service to set the entities. But a NullPointerException is being thrown if both or one is null. How do check if either of the two files (projectImg/chartImg) is null?

Here's my code so far:

public void uploadImages(MultipartFile projectImg, MultipartFile chartImg,  Long projectId) throws ValidationException, IOException {
    Project project = projectRepository.findOne(projectId);
    Project save = projectRepository.save(project);

    int maximumSizeMB = 15000000;

    if (!projectImg.isEmpty()) {
        if (projectImg.getSize() > maximumSizeMB) {
            throw new ValidationException("Image size is too big. Maximum size is 15 MB");
        }

        byte[] projectFile = ImageCompression.compressImage(projectImg);
        project.setProjectImg(projectFile);
        save.getProjectImg();
    }
    if (!chartImg.isEmpty()) {
        if (chartImg.getSize() > maximumSizeMB) {
            throw new ValidationException("Image size is too big. Maximum size is 15 MB");
        }

        byte[] chartFile = ImageCompression.compressImage(chartImg);
        project.setChartImg(chartFile);
        save.getChartImg();
    }
    projectRepository.save(project);
}

Thanks!

like image 418
Giorgio Di Feola Avatar asked Oct 25 '17 13:10

Giorgio Di Feola


3 Answers

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()) { ... }
like image 190
Frakcool Avatar answered Oct 22 '22 08:10

Frakcool


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

like image 21
Tadele Ayelegn Avatar answered Oct 22 '22 09:10

Tadele Ayelegn


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
like image 2
G_V Avatar answered Oct 22 '22 08:10

G_V