spring-mvcspring-framework-beansmultipartfile

Cannot convert value of type 'StandardMultipartFile' to required type 'java.lang.String'


I'm working with Spring Framework, and using some dependencies like Spring Jpa, Spring Web.

I were trying to add a photo in a register using MultipartFile but I got a error result. It returned a problem with the MultipartFile

I had this in my controller:

    @GetMapping("/registrarAdmin")
    public String registrarAdmin(Model model) {
        model.addAttribute("admin", new AdministradorEntity());
        return("registrarAdmin");
    }
    @PostMapping("/registrarAdmin")
    public String registroAdmin(@ModelAttribute("admin")AdministradorEntity adminFormulario,
            Model model, @RequestParam("fotoAdmin") MultipartFile foto) {
        adminService.crearAdmin(adminFormulario, foto);
        return "registrarAdmin";
    }

and the part of the MultipartFile (foto) implements is this:

public static String guardarImagen(MultipartFile foto){
        try {
            Path pathDire = Paths.get("src/main/resources/static/img/guardados/");
            if (!Files.exists(pathDire)) {
                Files.createDirectories(pathDire);
            }
            
            byte[] fotoBytes= foto.getBytes();
            Path pathImagen = Paths.get("src/main/resources/static/img/guardados/" + 
                    foto.getOriginalFilename());
            
                Files.write(pathImagen, fotoBytes);
                return foto.getOriginalFilename();
                
        } catch (IOException e) {
            // TODO: handle exception
            System.out.println("error al cargar la foto"+e.getMessage());
            return null;
        }
}

this is my output:

[2m2024-10-22T09:58:18.785-05:00[0;39m [33m WARN[0;39m [35m15572[0;39m [2m---[0;39m [2m[Proyecto_LP2] [nio-8080-exec-3][0;39m [2m[0;39m[36m.w.s.m.s.DefaultHandlerExceptionResolver[0;39m [2m:[0;39m Resolved [org.springframework.web.bind.MethodArgumentNotValidException: Validation failed for argument [0] in public java.lang.String com.proyecto.controller.AdminController.registroAdmin(com.proyecto.model.AdministradorEntity,org.springframework.ui.Model,org.springframework.web.multipart.MultipartFile): [Field error in object 'admin' on field 'foto': rejected value [org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile@731252d]; codes [typeMismatch.admin.foto,typeMismatch.foto,typeMismatch.java.lang.String,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [admin.foto,foto]; arguments []; default message [foto]]; default message [Failed to convert property value of type 'org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile' to required type 'java.lang.String' for property 'foto'; Cannot convert value of type 'org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile' to required type 'java.lang.String' for property 'foto': no matching editors or conversion strategy found]] ]

Finally, this is the implements of the method:

@Override
    public void crearAdmin(AdministradorEntity adminEntity, MultipartFile foto) {
        //Guardando image
        String nombreFoto= Utilitarios.guardarImagen(foto);
        adminEntity.setFoto(nombreFoto);
        //Hash password
        String hashPassword = Utilitarios.hashPassword(adminEntity.getContrasenia());
        adminEntity.setContrasenia(hashPassword);
        
        
        adminRepository.save(adminEntity);
    }

Currently I'm studying this in the institute so I don't know what to do. If you had an idea about the solution or maybe a different way to solve this code, I would like to know. THANKS!!


Solution

  • The error occurs because of the foto field in the AdministradorEntity class. Change the name of this field and its corresponding getter and setter to nombreFoto to solve the problem.