I have the below method to upload a file. When I get inputStream
from MultipartFile
in this line file.getInputStream()
I get a NullPointerException.
When I debug the MultipartFile, I get the below information
@PostMapping
public ResponseEntity<Void> fileUploadSave(@RequestPart(value = "file", required = true) MultipartFile file) {
service.fileUploadSave(file);
return new ResponseEntity<>(HttpStatus.OK);
}
private void fileUploadSave(MultipartFile file) {
try {
Path rootLocation = Paths.get(directory);
if (!Files.exists(rootLocation)) {
try {
Files.createDirectories(Paths.get(directory));
} catch (IOException e) {
throw new RuntimeException("Could not create upload folder!");
}
}
Path destinationFile = rootLocation.resolve(Paths.get(file.getOriginalFilename())).normalize().toAbsolutePath();
if (!destinationFile.getParent().equals(rootLocation.toAbsolutePath())) {
// This is a security check
throw new RuntimeException("Cannot store file outside current directory.");
}
try (InputStream inputStream = file.getInputStream()) {
Files.copy(inputStream, destinationFile, StandardCopyOption.REPLACE_EXISTING);
}
} catch (Exception e) {
throw new RuntimeException("Failed to store file.", e);
}
}
stacktrace
Caused by: java.lang.NullPointerException: null
at org.apache.tomcat.util.http.fileupload.disk.DiskFileItem.isInMemory(DiskFileItem.java:259)
at org.apache.tomcat.util.http.fileupload.disk.DiskFileItem.getInputStream(DiskFileItem.java:193)
at org.apache.catalina.core.ApplicationPart.getInputStream(ApplicationPart.java:100)
at org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile.getInputStream(StandardMultipartHttpServletRequest.java:251)
at com.entities.handlers.EstablishmentEntityManager.fileUploadSave(EstablishmentEntityManager.java:648)
... 24 common frames omitted