You are on page 1of 1

//image upload

//processing add contact form

@PostMapping("/process-contact")
public String processContact(@ModelAttribute Contact contact,
@RequestParam("profileImage")MultipartFile file,
Principal principal) { //multipart for image upload form
to db
try {//here allf fiels of contact will came
String name = principal.getName();
User user = this.userrepo.getuserbyusername(name);
//here we find out user inside we add contact
//processing and uploading file.
if(file.isEmpty()) {
//if the file is empty then try our message
System.out.println("files is empty");
}else { //file the file to folder and update the name to
connect
contact.setImage(file.getOriginalFilename());
File savefile = new ClassPathResource("static/img").getFile();
// Files.copy(in, target, options);
//if two image same then we need tow write logic
Path path = Paths.get(savefile.getAbsolutePath()
+File.separator+file.getOriginalFilename());
Files.copy(file.getInputStream(), path,
StandardCopyOption.REPLACE_EXISTING);
//Files.copy();
//option i checking if img is present then it will not take
System.out.println("Image is uploaded");}
contact.setUser(user);//give user to contact
user.getContacts().add(contact);//get list add to contact
this.userrepo.save(user);
System.out.println("Added to database");
System.out.println("Data"+contact);
} catch (Exception e) {
System.out.println("Error"+e.getMessage());
e.printStackTrace();
}
return "normal/add_contactform";
}
}

You might also like