vendredi 11 juin 2021

Uploading an image in springboot as binairy . but cant make it optional

I am uploading an image as binairy in springboot mongo ,it works but how do I make it that if there is no image save the other values without the image.

Here is my Model

public class Entity {

 @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 Address address;
    private BusinessInformation businessInformation;
    private Binary image;



//With contstructor and Getters and Setter

My controller is as follows ,believe I am makeing a mistake at the if image section

//Update or Create entity
    @RequestMapping(value = "/updateEntity", method = RequestMethod.POST, consumes = "multipart/form-data")
    public ResponseEntity<Entity> updateEntity(@RequestPart("entity") @Valid Entity entity, @RequestPart("file") @Valid Optional<MultipartFile> image) throws IOException {

        byte[] imageData = null;
        if (image.isPresent() && image.get() != null)
            imageData = image.get().getBytes();
        if (imageData == null && entity.getId() != null) {
            Optional<Entity> readEntity = entityRepository.findById(entity.getId());
            if (readEntity.get() != null)
                imageData = readEntity.get().getImage().getData();
        }
        if (imageData != null) {
            entity.setImage(new Binary(BsonBinarySubType.BINARY, imageData));
        }


    Entity result = entityRepository.save(entity);
    return ResponseEntity.ok().body(result);

}

When saving without my image I get a NullPointerException: null error

Aucun commentaire:

Enregistrer un commentaire