Home > Software engineering >  How to set a multipartfile parameter as "not required" in java with spring boot?
How to set a multipartfile parameter as "not required" in java with spring boot?

Time:07-12

my problem is that I have a controller developed in Java with Spring Boot in which I edit "Portfolio" entities. Here I get the different attributes to edit this entity and also an image. My idea is that if I receive the empty parameters, it will reassign to the entity the values it had before and only modify the attributes that were sent in the form with some value.

This works correctly when I test in Postman, but when I send the image attribute as "undefined" or as "null" from the form in angular, my controller in the back end shows me an error that says: Resolved [org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'file' is not present]

My idea is to make the "file" attribute which is a MultipartFile can be empty and have no problems.

My controller is as follows:

 @PutMapping("/portfolio/edit-data")
public Portfolio editPortfolio (@RequestParam("image")MultipartFile image,
                                  @ModelAttribute("port") Portfolio port,
                                  BindingResult result){
    
    Portfolio portOriginal = portServ.buscarPortfolio(Long.valueOf(1));
    
    if(!image.isEmpty()){
        String rutaAbsoluta = "C:\\Users\\Paul";
        try{
            byte[] bytesImg = image.getBytes();
            Path fullPath = Paths.get(absolutePath   "//"   image.getOriginalFilename());
            Files.write(fullPath, bytesImg);
            port.setImage(image.getOriginalFilename());
        }catch (IOException e){
        }
    }else{
        port.setImage(portOriginal.getImagen());
    }
    
    if("".equals(port.getName())){
        port.setName(portOriginal.getName());
    }
    if("".equals(port.getTitle())){
        port.setTitle(portOriginal.getTitle());
    }
    if("".equals(port.getIntroduction())){
        port.setIntroduction(portOriginal.getIntroduction());
    }
    if("".equals(port.getFooter())){
        port.setFooter(portOriginal.getFooter());
    }
 
    return portServ.editarPortfolio(port, Long.valueOf(1));
}

The following query is correct in Postman. So it would be useful to be able to submit an empty file in a form from angular.

Postman request

CodePudding user response:

Try @RequestParam(required = false) (no need for the name to be specified with the value param, because spring takes the variable name by default and in your case they're the same)

You're method definition would look like this:

@PutMapping("/portfolio/edit-data")
public Portfolio editPortfolio (@RequestParam(required = false) MultipartFile image,
                                @ModelAttribute Portfolio port,
                                BindingResult result)
  • Related