added many images in post
This commit is contained in:
@@ -44,7 +44,7 @@ public class PostService {
|
||||
private final UserService userService;
|
||||
private final FavoriteRepository favoriteRepository;
|
||||
|
||||
public PostRequest create(PostRequest request, MultipartFile image) {
|
||||
public PostRequest create(PostRequest request, List<MultipartFile> images) {
|
||||
|
||||
Post post = mapper.toEntity(request);
|
||||
post.setCreatedAt(LocalDateTime.now());
|
||||
@@ -52,21 +52,32 @@ public class PostService {
|
||||
post.setUser(userService.getCurrentUser()); // присваиваем текущего пользователя
|
||||
repository.save(post); // сначала сохраняем post, чтобы получить id
|
||||
|
||||
if (image != null && !image.isEmpty()) {
|
||||
String filename = UUID.randomUUID() + "_" + image.getOriginalFilename();
|
||||
if (images != null && !images.isEmpty()) {
|
||||
Path uploadDir = Paths.get("uploads");
|
||||
|
||||
try {
|
||||
Files.createDirectories(uploadDir);
|
||||
Files.copy(image.getInputStream(), uploadDir.resolve(filename));
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("Не удалось сохранить файл: " + filename, e);
|
||||
throw new RuntimeException("Не удалось создать директорию загрузки", e);
|
||||
}
|
||||
|
||||
Image img = new Image();
|
||||
img.setUrl("/uploads/" + filename);
|
||||
img.setPost(post);
|
||||
imageRepository.save(img);
|
||||
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);
|
||||
}
|
||||
|
||||
Image img = new Image();
|
||||
img.setUrl("/uploads/" + filename);
|
||||
img.setPost(post);
|
||||
imageRepository.save(img);
|
||||
}
|
||||
}
|
||||
|
||||
return request;
|
||||
@@ -146,8 +157,7 @@ public class PostService {
|
||||
.toList();
|
||||
}
|
||||
|
||||
public PostResponse update(Long id, PostRequest request, MultipartFile image) {
|
||||
|
||||
public PostResponse update(Long id, PostRequest request, List<MultipartFile> images, List<String> existingUrls) {
|
||||
Post post = repository.findById(id)
|
||||
.orElseThrow(() -> new ApiException(
|
||||
ErrorCode.NOT_FOUND,
|
||||
@@ -162,41 +172,59 @@ public class PostService {
|
||||
}
|
||||
post.setPhone(request.getPhone());
|
||||
post.setType(request.getType());
|
||||
if (request.getLatitude() != null && request.getLongitude() != null){
|
||||
|
||||
if (request.getLatitude() != null && request.getLongitude() != null) {
|
||||
post.setLatitude(request.getLatitude());
|
||||
post.setLongitude(request.getLongitude());
|
||||
String address = nominatimService.getAddress(request.getLatitude().toString(), request.getLongitude().toString());
|
||||
String address = nominatimService.getAddress(
|
||||
request.getLatitude().toString(), request.getLongitude().toString());
|
||||
post.setCity(address);
|
||||
} else {
|
||||
post.setCity(request.getAddress());
|
||||
}
|
||||
|
||||
if (image != null && !image.isEmpty()) {
|
||||
// удаляем старые картинки с диска
|
||||
post.getImages().forEach(img -> {
|
||||
try {
|
||||
Files.deleteIfExists(Paths.get("." + img.getUrl()));
|
||||
} catch (IOException e) {
|
||||
log.warn("Не удалось удалить файл: {}", img.getUrl());
|
||||
}
|
||||
});
|
||||
// очищаем список (orphanRemoval = true удалит из БД)
|
||||
post.getImages().clear();
|
||||
List<String> keepUrls = existingUrls != null ? existingUrls : List.of();
|
||||
|
||||
// сохраняем новую картинку
|
||||
String filename = UUID.randomUUID() + "_" + image.getOriginalFilename();
|
||||
// удаляем те картинки, которых нет среди "оставленных" с фронта
|
||||
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());
|
||||
}
|
||||
});
|
||||
|
||||
post.getImages().removeAll(toRemove); // orphanRemoval = true удалит из БД
|
||||
|
||||
// добавляем новые загруженные файлы
|
||||
if (images != null && !images.isEmpty()) {
|
||||
Path uploadDir = Paths.get("uploads");
|
||||
try {
|
||||
Files.createDirectories(uploadDir);
|
||||
Files.copy(image.getInputStream(), uploadDir.resolve(filename));
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("Не удалось сохранить файл: " + filename, e);
|
||||
throw new RuntimeException("Не удалось создать директорию загрузки", e);
|
||||
}
|
||||
|
||||
Image img = new Image();
|
||||
img.setUrl("/uploads/" + filename);
|
||||
img.setPost(post);
|
||||
post.getImages().add(img);
|
||||
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);
|
||||
}
|
||||
|
||||
Image img = new Image();
|
||||
img.setUrl("/uploads/" + filename);
|
||||
img.setPost(post);
|
||||
post.getImages().add(img);
|
||||
}
|
||||
}
|
||||
|
||||
Post updated = repository.save(post);
|
||||
|
||||
Reference in New Issue
Block a user