我正在尝试将带有额外数据的文件保存为 springboot 中的可选文件。因此,用户应该可以选择添加图像或不添加图像。没有图像时,我收到一个无价值错误。当有图像时,一切都很好。
@RequestMapping(value = "/updateCustomer", method = RequestMethod.POST, consumes = "multipart/form-data")
public ResponseEntity<?> updateCustomer(@RequestPart("customer") @Valid Customer customer, @RequestPart("file") @Valid Optional<MultipartFile> image) throws IOException {
byte[] imageData = null;
if (image.isPresent() && image.get() != null)
imageData = image.get().getBytes();
if (imageData == null && customer.getId() != null) {
Optional<Customer> readCustomer = customerRepository.findById(customer.getId());
if (readCustomer.get() != null)
imageData = readCustomer.get().getImage().getData();
}
if (imageData != null) {
customer.setImage(new Binary(BsonBinarySubType.BINARY, imageData));
}
Customer result = customerRepository.save(customer);
return ResponseEntity.ok().body(result);
}
使用控制器的型号
public class Customer {
@Id
private String id;
private String username;
private String name;
private String surname;
private String dob;
private String position;
private String email;
private String contactNo;
private String status;
private Integer notificationValue;
private Address address;
private BusinessInformation businessInformation;
private Binary image;
private List<UserRolls> userRolls;
private List<CustomerITMModules> entityITMModules;
我得到的错误
java.lang.NullPointerException: Cannot invoke "org.bson.types.Binary.getData()" because the return value of "com.mqa.modules.Admin.mst_Entity.models.Customer.getImage()" is null