将 MultipartFile 转换为所需的类型 byte[] thymeleaf 错误

Posted

技术标签:

【中文标题】将 MultipartFile 转换为所需的类型 byte[] thymeleaf 错误【英文标题】:convert MultipartFile to required type byte[] thymeleaf error 【发布时间】:2021-06-11 09:50:59 【问题描述】:

我收到这个错误,不知道为什么

出现意外错误(类型=错误请求,状态=400)。 object='client' 的验证失败。错误计数:1 org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 个错误 字段“图像”上的对象“客户端”中的字段错误:拒绝值 [org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile@42df4d2d];代码 [typeMismatch.client.image,typeMismatch.image,typeMismatch.[B,typeMismatch];参数 [org.springframework.context.support.DefaultMessageSourceResolvable: 代码 [client.image,image];论据 [];默认消息[图像]];默认消息 [无法将类型“org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile”的属性值转换为属性“图像”所需的类型“字节 []”;嵌套异常是 java.lang.IllegalArgumentException:无法将类型“org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile”的值转换为属性“图像 [0]”所需的类型“字节”:PropertyEditor [org.springframework. beans.propertyeditors.CustomNumberEditor] 返回类型为 'org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile' 的不适当值]

实体:

@Entity
@Table(name = "Client")
public class Client implements Serializable 
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="idClient")
private Long idClient;
@Column(name="nom")
private String nomClient;
@Column(name="prenom")
private String prenomClient;
@Column(name="datedenaissance")
@DateTimeFormat(pattern = "yyyy-MM-dd")
@Temporal(TemporalType.DATE)
private Date datedenaissanceClient;
@Column(name="typepiece")
private String typepieceClient;
@Column(name="numeropiece")
private int numeropieceClient;
@Column(name="numerotel")
private Long numerotelClient;
@Column(name="email")
private String emailClient;
@Column(name="adresse")
private String adresseClient;
@Column(name="rendezvous")
@DateTimeFormat(pattern = "yyyy-MM-dd")
@Temporal(TemporalType.DATE)
private Date rendezvous;
@Column(name="temps")
@DateTimeFormat(pattern = "hh:mm")
@Temporal(TemporalType.TIME)
private Date temps;
@Column(name="tempsfin")
@DateTimeFormat(pattern = "hh:mm")
@Temporal(TemporalType.TIME)
private Date tempsfin;
@OneToMany(cascade = CascadeType.ALL, mappedBy="clients")
private List<Compte> comptes;
@Lob
@Column(name="image")
private byte[] image;


public static long getSerialversionuid() 
    return serialVersionUID;

public Long getIdClient() 
    return idClient;

public void setIdClient(Long idClient) 
    this.idClient = idClient;

public String getNomClient() 
    return nomClient;

public void setNomClient(String nomClient) 
    this.nomClient = nomClient;

public String getPrenomClient() 
    return prenomClient;

public void setPrenomClient(String prenomClient) 
    this.prenomClient = prenomClient;

public Date getDatedenaissanceClient() 
    return datedenaissanceClient;

public void setDatedenaissanceClient(Date datedenaissanceClient) 
    this.datedenaissanceClient = datedenaissanceClient;

public String getTypepieceClient() 
    return typepieceClient;

public void setTypepieceClient(String typepieceClient) 
    this.typepieceClient = typepieceClient;

public Date getTempsfin() 
    return tempsfin;

public void setTempsfin(Date tempsfin) 
    this.tempsfin = tempsfin;


public int getNumeropieceClient() 
    return numeropieceClient;

public void setNumeropieceClient(int numeropieceClient) 
    this.numeropieceClient = numeropieceClient;

public Long getNumerotelClient() 
    return numerotelClient;

public void setNumerotelClient(Long numerotelClient) 
    this.numerotelClient = numerotelClient;

public String getEmailClient() 
    return emailClient;

public void setEmailClient(String emailClient) 
    this.emailClient = emailClient;

public String getAdresseClient() 
    return adresseClient;

public void setAdresseClient(String adresseClient) 
    this.adresseClient = adresseClient;

public Date getRendezvous() 
    return rendezvous;

public void setRendezvous(Date rendezvous) 
    this.rendezvous = rendezvous;

public Date getTemps() 
    return temps;

public void setTemps(Date temps) 
    this.temps = temps;

public List<Compte> getComptes() 
    return comptes;

public void setComptes(List<Compte> comptes) 
    this.comptes = comptes;


public Client(Long idClient, String nomClient, String prenomClient, Date datedenaissanceClient,
        String typepieceClient, int numeropieceClient, Long numerotelClient, String emailClient,
        String adresseClient, Date rendezvous, Date temps, Date tempsfin, List<Compte> comptes, byte[] image) 
    super();
    this.idClient = idClient;
    this.nomClient = nomClient;
    this.prenomClient = prenomClient;
    this.datedenaissanceClient = datedenaissanceClient;
    this.typepieceClient = typepieceClient;
    this.numeropieceClient = numeropieceClient;
    this.numerotelClient = numerotelClient;
    this.emailClient = emailClient;
    this.adresseClient = adresseClient;
    this.rendezvous = rendezvous;
    this.temps = temps;
    this.tempsfin = tempsfin;
    this.comptes = comptes;
    this.image = image;

public byte[] getImage() 
    return image;

public void setImage(byte[] image) 
    this.image = image;

@Override
public String toString() 
    return "Client [idClient=" + idClient + ", nomClient=" + nomClient + ", prenomClient=" + 
   prenomClient
            + ", datedenaissanceClient=" + datedenaissanceClient + ", typepieceClient=" + 
  typepieceClient
            + ", numeropieceClient=" + numeropieceClient + ", numerotelClient=" + numerotelClient + 
  ", emailClient="
            + emailClient + ", adresseClient=" + adresseClient + ", rendezvous=" + rendezvous + ", 
     temps=" + temps
            + ", tempsfin=" + tempsfin + ", comptes=" + comptes + ", image=" + Arrays.toString(image) 
       + "]";

public Client() 
    super();
    // TODO Auto-generated constructor stub

public Client(Long idClient, String nomClient, String prenomClient, Date datedenaissanceClient,
        String typepieceClient, int numeropieceClient, Long numerotelClient, String emailClient,
        String adresseClient, Date rendezvous, Date temps, List<Compte> comptes) 
    super();
    this.idClient = idClient;
    this.nomClient = nomClient;
    this.prenomClient = prenomClient;
    this.datedenaissanceClient = datedenaissanceClient;
    this.typepieceClient = typepieceClient;
    this.numeropieceClient = numeropieceClient;
    this.numerotelClient = numerotelClient;
    this.emailClient = emailClient;
    this.adresseClient = adresseClient;
    this.rendezvous = rendezvous;
    this.temps = temps;
    this.comptes = comptes;












 

服务:

 @Override
public void addClient(Client client)
    // TODO Auto-generated method stub
    this.clientRepository.save(client);

控制器:

@RequestMapping(value =  "/saveClient" , method = RequestMethod.POST, consumes = "multipart/form-data")
public String saveClient(@ModelAttribute("client") Client client,Model model,@ModelAttribute("compte") Compte compte,@ModelAttribute("carte") Carte carte,
        @ModelAttribute("agence") Agence agence,MultipartHttpServletRequest request,final @RequestParam("image") MultipartFile file) throws IOException  
    compte.setClients(client);
    String uploadDirectory = request.getServletContext().getRealPath(uploadFolder);
    log.info("uploadDirectory:: " + uploadDirectory);
    String fileName = file.getOriginalFilename();
    String filePath = Paths.get(uploadDirectory, fileName).toString();
    log.info("FileName: " + file.getOriginalFilename());
    if (fileName == null || fileName.contains("..")) 
        model.addAttribute("invalid", "Sorry! Filename contains invalid path sequence \" + fileName");
        
    
    try 
        File dir = new File(uploadDirectory);
        if (!dir.exists()) 
            log.info("Folder Created");
            dir.mkdirs();
        
        // Save the file locally
        BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(filePath)));
        stream.write(file.getBytes());
        stream.close();
     catch (Exception e) 
        log.info("in catch");
        e.printStackTrace();
    
    byte[] imageData = file.getBytes();
    client.setImage(imageData);
    Date v = client.getTemps();
    //Date dNow = new Date( ); // Instantiate a Date object
    Calendar cal = Calendar.getInstance();
    cal.setTime(v);
    cal.add(Calendar.AM_PM, 0);
    cal.add(Calendar.MINUTE, 30);
    v = cal.getTime();
    client.setTempsfin(v);
    clientMetier.addClient(client);
    compteMetier.addCompte(compte);
    agence.setCompteagence(compte);
    compte.setAgencecompte(agence);
    agenceMetier.addAgence(agence);
    model.addAttribute("compte",compte);
    model.addAttribute("agence",agence);
    return "compte";

html

<form th:action="@/saveClient" method="POST"
                    th:object="$client" enctype="multipart/form-data">
<div class="p-col-12">
<label class="p1">Image</label>
<input type="file" class="form-control" placeholder="" name="image" id="image" th:field="*image">
                              

【问题讨论】:

【参考方案1】:

您不应该直接使用您的实体作为表单对象,因为您需要为图像使用不同的类型。

创建一个单独的ClientFormData 对象以在具有Client 的所有字段的控制器中使用,但对于图像使用MultipartFile

public class ClientFormData 
   // other fields here
   private MultipartFile image;

   public static ClientFormData fromClient(Client client) 
       // copy over fields
   

在控制器中,从 MultipartFile 中获取字节并将其复制到您的 Client 实体中。

【讨论】:

以上是关于将 MultipartFile 转换为所需的类型 byte[] thymeleaf 错误的主要内容,如果未能解决你的问题,请参考以下文章

无法将 java.lang.String 类型的属性值转换为所需的 java.time.LocalDateTime 类型

无法将 java.lang.String 类型的属性值转换为所需的 java.util.Date 类型

无法将 java.lang.String 类型的值转换为所需的 java.util.Date 类型

如何查询/将数据转换为所需的格式

将数据帧转换为所需的字典格式

如何将 python 字典转换为所需的格式