1

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

enter image description here

@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
samabcde
  • 6,988
  • 2
  • 25
  • 41
Aymen Kanzari
  • 1,765
  • 7
  • 41
  • 73
  • @Hulk i added it – Aymen Kanzari Sep 20 '21 at 15:00
  • Source code for the is publicly available if you are interested in investigating this: [Tomcat DiskFileItem](https://apache.googlesource.com/tomcat/+/7960a66affb955dcdb49a3d78d646cdf7a98eb52/java/org/apache/tomcat/util/http/fileupload/disk/DiskFileItem.java), but this seems a different revision from the one you are using, as the line number would point to a comment line there. – Hulk Sep 20 '21 at 15:12
  • Please provide a [mcve], showing how you get a reference to this `MultipartFile`. – Sotirios Delimanolis Sep 20 '21 at 15:16

0 Answers0