fixed image locale storage on minio
This commit is contained in:
@@ -47,43 +47,30 @@ public class PostService {
|
||||
private final NominatimService nominatimService;
|
||||
private final UserService userService;
|
||||
private final FavoriteRepository favoriteRepository;
|
||||
private final FileStorageService fileStorageService;
|
||||
|
||||
public PostRequest create(PostRequest request, List<MultipartFile> images) {
|
||||
|
||||
Post post = mapper.toEntity(request);
|
||||
post.setCreatedAt(LocalDateTime.now());
|
||||
post.setStatus(PostStatus.ACTIVE);
|
||||
post.setUser(userService.getCurrentUser()); // присваиваем текущего пользователя
|
||||
repository.save(post); // сначала сохраняем post, чтобы получить id
|
||||
post.setUser(userService.getCurrentUser());
|
||||
repository.save(post);
|
||||
|
||||
if (images != null && !images.isEmpty()) {
|
||||
Path uploadDir = Paths.get("uploads");
|
||||
try {
|
||||
Files.createDirectories(uploadDir);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("Не удалось создать директорию загрузки", e);
|
||||
}
|
||||
|
||||
for (MultipartFile image : images) {
|
||||
if (image == null || image.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
String filename = UUID.randomUUID() + "_" + image.getOriginalFilename();
|
||||
|
||||
try {
|
||||
Files.copy(image.getInputStream(), uploadDir.resolve(filename));
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("Не удалось сохранить файл: " + filename, e);
|
||||
}
|
||||
String objectKey = fileStorageService.uploadFile(image);
|
||||
|
||||
Image img = new Image();
|
||||
img.setUrl("/uploads/" + filename);
|
||||
img.setUrl(objectKey); // храним ключ MinIO, а не путь на диске
|
||||
img.setPost(post);
|
||||
imageRepository.save(img);
|
||||
}
|
||||
}
|
||||
|
||||
return request;
|
||||
}
|
||||
|
||||
@@ -187,43 +174,30 @@ public class PostService {
|
||||
|
||||
List<String> keepUrls = existingUrls != null ? existingUrls : List.of();
|
||||
|
||||
// удаляем те картинки, которых нет среди "оставленных" с фронта
|
||||
List<Image> toRemove = post.getImages().stream()
|
||||
.filter(img -> !keepUrls.contains(img.getUrl()))
|
||||
.toList();
|
||||
|
||||
toRemove.forEach(img -> {
|
||||
try {
|
||||
Files.deleteIfExists(Paths.get("." + img.getUrl()));
|
||||
} catch (IOException e) {
|
||||
log.warn("Не удалось удалить файл: {}", img.getUrl());
|
||||
fileStorageService.deleteFile(img.getUrl());
|
||||
} catch (Exception e) {
|
||||
log.warn("Не удалось удалить файл из хранилища: {}", img.getUrl(), e);
|
||||
}
|
||||
});
|
||||
|
||||
post.getImages().removeAll(toRemove); // orphanRemoval = true удалит из БД
|
||||
post.getImages().removeAll(toRemove);
|
||||
|
||||
// добавляем новые загруженные файлы
|
||||
if (images != null && !images.isEmpty()) {
|
||||
Path uploadDir = Paths.get("uploads");
|
||||
try {
|
||||
Files.createDirectories(uploadDir);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("Не удалось создать директорию загрузки", e);
|
||||
}
|
||||
|
||||
for (MultipartFile image : images) {
|
||||
if (image == null || image.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
String filename = UUID.randomUUID() + "_" + image.getOriginalFilename();
|
||||
try {
|
||||
Files.copy(image.getInputStream(), uploadDir.resolve(filename));
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("Не удалось сохранить файл: " + filename, e);
|
||||
}
|
||||
|
||||
String objectKey = fileStorageService.uploadFile(image);
|
||||
|
||||
Image img = new Image();
|
||||
img.setUrl("/uploads/" + filename);
|
||||
img.setUrl(objectKey);
|
||||
img.setPost(post);
|
||||
post.getImages().add(img);
|
||||
}
|
||||
@@ -235,7 +209,6 @@ public class PostService {
|
||||
|
||||
@CacheEvict(value = {"posts", "post"}, allEntries = true)
|
||||
public void delete(Long id) {
|
||||
|
||||
Post post = repository.findById(id)
|
||||
.orElseThrow(() -> new ApiException(
|
||||
ErrorCode.NOT_FOUND,
|
||||
@@ -243,6 +216,15 @@ public class PostService {
|
||||
HttpStatus.NOT_FOUND
|
||||
));
|
||||
|
||||
// без этого файлы останутся в MinIO мусором после удаления объявления
|
||||
post.getImages().forEach(img -> {
|
||||
try {
|
||||
fileStorageService.deleteFile(img.getUrl());
|
||||
} catch (Exception e) {
|
||||
log.warn("Не удалось удалить файл из хранилища: {}", img.getUrl(), e);
|
||||
}
|
||||
});
|
||||
|
||||
repository.delete(post);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user