尝试将 springboot 中的文件保存为可选

问题描述

我正在尝试将文件保存为带有额外数据的 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 Business@R_812_4045@ion business@R_812_4045@ion;
    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 作为方法参数的原因是什么?

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

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

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

,

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

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