我正在尝试上传图片,但问题是类联系人的字段图片



这是我提交添加/联系人时收到的错误。

There was an unexpected error (type=Bad Request, status=400).
Validation failed for object='contact'. Error count: 1
org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'contact' on field 'image': rejected value [org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile@234005aa]; codes [typeMismatch.contact.image,typeMismatch.image,typeMismatch.java.lang.String,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [contact.image,image]; arguments []; default message [image]]; default message [Failed to convert property value of type 'org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile' to required type 'java.lang.String' for property 'image'; nested exception is 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]

控制器。。。。

@PostMapping("/process-contact")
public String processContact(@ModelAttribute Contact contact,
@RequestParam("image") MultipartFile file,
Principal principal,
HttpSession session) {

try {
String name = principal.getName();
User user = this.userRepository.getUserByUserName(name);

//processing and uploading file
if(file.isEmpty()) {
System.out.println("Empty file");
contact.setImage("man.jpg");
}
else {
contact.setImage(file.getOriginalFilename());

File saveFile = new ClassPathResource("static/image").getFile();

Path path = Paths.get(saveFile.getAbsolutePath()+File.pathSeparator+file.getOriginalFilename());

Files.copy(file.getInputStream(),path,StandardCopyOption.REPLACE_EXISTING );

System.out.println("Image is uploaded");
}

//important...
contact.setUser(user);
user.getContacts().add(contact);
//......
this.userRepository.save(user);


System.out.println("DATA : "+contact);
System.out.println("Contact Added to Database");

//message success....
session.setAttribute("message", new Message("Your Contact is Added !! Add More..", "success"));


} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();

//message error..
session.setAttribute("message", new Message("Soemthing Went Wrong !! Try Again...", "danger"));
}

return "normal/add_contact_form";
}
````
the add contact form html file...
<form action="#"
th:object="${contact}"
enctype="multipart/form-data"
method="post"
th:action="@{/userr/process-contact}"
class="mt-2"
>


<!-- Contact Description  -->

<div class="form-group mt-3 ms-5">

<textarea name="description" id="mytextarea" cols="50" rows="10" placeholder="Enter Contact Description"></textarea>

</div>

<!-- Contact Image -->

<div class="custom-file mt-3">

<input type="file" name="image">

</div>

enter image description here

[enter image description here][2]

[1]: https://i.stack.imgur.com/TMhP1.png
[2]: https://i.stack.imgur.com/emBS0.png

the contact.java file is below
@Entity
@Table(name = "CONTACT")
public class Contact {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int cId;
private String name;
private String secondName;
private String work;
private String email;
private String phone;
private String image;
@Column(length = 1000)
private String description;

@ManyToOne
private User user;


  1. 根据注释部分的建议更改您的fieldName
  2. 目前,您正在系统中保存您的图像。要获取它,您必须再次从系统中读取它。另一件事是,在调用file.getOriginalFileName()方法时,要小心客户端提供的名称,最好是设置自己的名称。看看这个
  3. 若要将图像存储在数据库中,请将image字符串字段更改为@Lob(type = LobType.BLOB) private byte[] your_fieldName;。在将文件保存到数据库之前,请在此处设置文件内容。然后您可以直接获取图像数据以及其他字段

相关内容

最新更新