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!
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With