尝试在 spring boot 中将文件保存为可选文件

Trying to save a file in springboot as an optional

我正在尝试将文件保存为带有额外数据的 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

如果您也分享错误的堆栈跟踪,通常会有所帮助。

似乎只有在请求中存在相应的 RequestPart 时,框架才能创建 Optional。所以问题是您使用 Optional 作为方法参数的原因是什么?

您在代码中进行的所有检查几乎都不会受益于可选类型的参数。

IMO,您应该重组代码以简单地检查 'image' 参数是否为 null 并采取相应措施。

此外,方法参数上的@Valid 注解'image' 可能是不必要的。 'customer' 方法参数的 @Valid 注释只有在 Customer class 本身被相应地注释时才有意义。

所以采纳了大家的意见。对可选图像的控制器进行了更改。不是最有效但有效

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