Cannot convert value of type MultipartFile to String

Issue

When I added validation for field Name I got an error:

Validation failed for object=’item’. Error count: 1org.springframework.validation.BindException
Field error in object ‘item’ on field ‘image’: rejected java.lang.IllegalStateException: Cannot convert value of type ‘org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile’ to required type ‘java.lang.String’ for property ‘image’: no matching editors or conversion strategy found

Entity, class Item

@Entity
@Table(name = "items")
public class Item {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private int id;

@NotBlank(message = "Введите наименование")
@Column(name = "name")
private String name;

@JsonIgnore
@Lob
@Column(name = "image")
private String image;
}

Main controller

@PostMapping("/items")
public String add(
    @Valid Item item,
    @RequestParam("image") MultipartFile file,
    BindingResult bindingResult,
    Model model
) throws IOException {

if (bindingResult.hasErrors()){
    Map<String, String> errorsMap = ControllerUtils.getErrors(bindingResult);
    model.mergeAttributes(errorsMap);
    model.addAttribute("item", item);
} else {
    if (file != null && !file.getOriginalFilename().isEmpty()) {
        byte[] data = file.getBytes();
        String imageString = Base64.getEncoder().encodeToString(data);
        item.setImage(imageString);
    }
    model.addAttribute("item", null);
    itemService.saveItem(item);
}

Solution

I solved the problem by creating new formParams (quite similar with entity Items with all validation parameters) and put this form as a parameter to the post method.

@PostMapping("/items/save")
public String add(@AuthenticationPrincipal User user, @Valid ItemInputParams formParams,
                  BindingResult bindingResult, Model model) throws IOException {

    if (bindingResult.hasErrors()){
        Map<String, String> errorsMap = 
ControllerUtils.getErrors(bindingResult);
        model.mergeAttributes(errorsMap);
        model.addAttribute("item", formParams);
        return initItems(null, model);
    }

    Item item = new Item();
    item.setName(formParams.getName());
    (...)

    MultipartFile file = formParams.getImage();
    if (file != null && !file.getOriginalFilename().isEmpty()) {
        byte[] data = file.getBytes();
        String imageString = Base64.getEncoder().encodeToString(data);
        item.setImage(imageString);
    }
    (...)
}

Answered By – Tom

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published