This is my Personne class:
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Personne {
@Id
@GeneratedValue()
private int id;
@Column(length = 20 , nullable = false )
private String frist_Name;
@Column(length = 20 , nullable = false )
private String last_Name;
@Column(length = 10 , nullable = false , unique = true )
private String cni;
private String car_plate;
private String Adress;
@Column(length = 45 , nullable = true)
private String image;
@Transient
public String getImagePath() {
if (image == null || id == 0) return null;
return "/user-photos/"+ id + "/" + image;
}
}
this is my Controller : savePersonne Methode that store the personne it works fine but maybe i'm forgeting something
@PostMapping("/Personnes/save")
public String savePersonne(Personne personne, @RequestParam("file") MultipartFile file) throws IOException {
String fileName = StringUtils.cleanPath(file.getOriginalFilename());
personne.setImage(fileName);
Personne savedPerso = repo.save(personne);
String uploadDir = "./user-photos/" + savedPerso.getId();
FileUploadUtil.saveFile(uploadDir, fileName, file);
return "redirect:/personnes";
}
And this is the saveFile methode code :
public static void saveFile(String uploadDir, String fileName,
MultipartFile multipartFile) throws IOException {
Path uploadPath = Paths.get(uploadDir);
if (!Files.exists(uploadPath)) {
Files.createDirectories(uploadPath);
}
try (InputStream inputStream = multipartFile.getInputStream()) {
Path filePath = uploadPath.resolve(fileName);
System.out.println(filePath.toFile().getAbsolutePath());
Files.copy(inputStream, filePath, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException ioe) {
throw new IOException("Could not save image file: " + fileName, ioe);
}
the folder /user-photos/ is created and it store the image but some reason the image can't be displayed
this my view code using thymleaf as a server side template:
<tbody>
<th:block th:each="personne : ${listPersonnes}">
<tr>
<td><img th:src="@{${personne.imagePath}}" style="width: 100px;height: 100px"></td>
<td>[[${personne.frist_Name}]]</td>
<td>[[${personne.last_Name}]]</td>
<td>[[${personne.adress}]]</td>
<td>[[${personne.cni}]]</td>
<td>[[${personne.car_plate}]]</td>
<td>
<a th:href="@{'/personnes/edit/' + ${personne.id}}">Edit</a>
<a th:href="@{'/personnes/delete/' + ${personne.id}}">Delete</a>
</td>
</tr>
</th:block>
</tbody>