0

I am trying to save a file as an optional in springboot with extra data. So the user should have the option to add an image or not to add an image. I recieve an no value error when there is no image. Everything saves fine when there is an image.

@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);
    }

Model used ing controller

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;

Error I'm getting

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
Zoe
  • 27,060
  • 21
  • 118
  • 148
  • Your use of `Optional` is wrong. You should use `ifPresent` not `isPresent` and `get` together as that will lead to issues. – M. Deinum Jul 07 '21 at 06:09
  • Hi thank you for responding, can you give an example of how it should look. –  Jul 07 '21 at 08:37

2 Answers2

0

It would generally be helpful if you shared the stack trace of the error as well.

It seems like the framework can only create an Optional if the corresponding RequestPart is present in the request. So the question is what is the reason you are using an Optional as a method parameter?

All the checks you make in the code hardly benefit from the parameter being of type Optional.

IMO you should restructure the code to simply check whether the 'image' parameter is null or not and act accordingly.

Furthermore, the @Valid annotation on the method parameter 'image' is probably unnecessary. The @Valid annotation to the 'customer' method parameter only makes sense if the Customer class itself is annotated accordingly.

0

So took everyone's advice. Made a change to the controller for optional image. Not the most efficient but it works

 @RequestMapping(value = "/updateCustomer", method = RequestMethod.POST, consumes = "multipart/form-data")
    public ResponseEntity<?> updateCustomer(@RequestPart("customer") @Valid Customer customer,
                                            @RequestParam(name="file", required=false) MultipartFile image) throws IOException {

//Create New User
if(customer.getId() == ""){
    System.out.println("New User");
}else if(customer != null  ){  //On Edit User
    Customer user = this.customerRepository.findUsersByEmail(customer.getEmail());
    if(image == null && user.getImage() != null){  // If User has image save same image
        byte[] existingImage = user.getImage().getData();
        customer.setImage(new Binary(BsonBinarySubType.BINARY, existingImage));
        System.out.println(customer.getName());
    }

}
        //Save New Image
        if(customer.getId() != null  && image!= null){
            System.out.println("TestNew");
            byte[] newImage = image.getBytes();
            customer.setImage(new Binary(BsonBinarySubType.BINARY, newImage));
        }


        


        Customer result = customerRepository.save(customer);
        return ResponseEntity.ok().body(result);
    }
Wenfang Du
  • 8,804
  • 9
  • 59
  • 90