here is the error I am getting when I submit the add/contact.
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]
The controller ....
@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}"
>
<!-- Contact Description -->
<div >
<textarea name="description" id="mytextarea" cols="50" rows="10" placeholder="Enter Contact Description"></textarea>
</div>
<!-- Contact Image -->
<div >
<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;
CodePudding user response:
- Change your fieldName as suggested in the comment section.
- currently, you are saving your image in the system. To get it, you must read it from the system again. Another thing, while calling the
file.getOriginalFileName()method, be careful with the client provided name, better if you set your own. See this - If you want to store your image in database, change your
imageString field with@Lob(type = LobType.BLOB) private byte[] your_fieldName;. Set th file content here before saving it to database. Then you can directly get image-data along with other fields
CodePudding user response:
It would be very helpful, if you would share your code. But with the Errormessage it seems like you are trying to cast a 'StandardMultipartFile' into a 'String'.
Make sure your Parameters are all correct.
