我有以下方法来上传文件。当我inputStream
从这MultipartFile
一行file.getInputStream()
得到一个 NullPointerException。
当我调试 MultipartFile 时,我得到以下信息
@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);
}
}
堆栈跟踪
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