当前位置: 首页 > 知识库问答 >
问题:

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

尚鸿才
2023-03-14

我收到这个错误idk为什么

有一个意外的错误(类型=错误请求,状态=400)。对象=客户端的验证失败。错误数:1org.springframework.validation.BindException:org.springframework.validation.BeanProperty tyBindingResult: 1错误字段“图像”上对象“客户端”中的字段错误:拒绝值[org.springframework.web.multipart.support.Standard ardMultipartHttpServletRequest$StandardMultipartFile@42df4d2d];代码[typeMismatch.client.image, typeMismatch.image, typeMismate。[B,类型不匹配];参数[org.springframework.context.support.DefaultMessageSourceResolable:代码[client.image,图像];参数[];默认消息[图像]];默认消息[无法将属性值的类型'org.springframework.web.multipart.support.Standard ardMultipartHttpServletRequest$Standard ardMultipartFile'转换为所需的类型'byte[]'的属性'image';嵌套异常是java.lang.IllegalArgumentException:无法将值的类型'org.springframework.web.multipart.support.Standard ardMultipartHttpServletRequest$Standard ardMultipartFile'转换为所需的类型'byte'的属性'图像[0]':属性编辑器[org.springframework.beans.propertyeditors.CustomNumberEditor]返回不适当的值的类型'org.springframework.web.multipart.support.Standard ardMultipartHttpServletRequest$Standard ardMultipartFile']

实体:

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

超文本标记语言:

<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个答案

唐炳
2023-03-14

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

创建一个单独的ClientFormData对象以在控制器中使用,该对象具有客户机的所有字段,但对于图像使用多部分文件:

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

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

在控制器中,从多部分文件中获取字节,并将其复制到您的客户机实体中。

 类似资料: