Skip to content

Commit

Permalink
이미지
Browse files Browse the repository at this point in the history
  • Loading branch information
Johyunik committed Dec 4, 2023
1 parent b9f0c1f commit 7bc70c8
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 11 deletions.
20 changes: 11 additions & 9 deletions src/main/java/com/weatherfit/board/service/BoardService.java
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,17 @@ public void patchBoard(int boardId, String boardJson, MultipartFile[] images, St
throw new RuntimeException(e);
}


if (boardUpdateDTO.getDeletedImages() != null) {
for (Integer imageId : boardUpdateDTO.getDeletedImages()) {
Optional<ImageEntity> optionalImageEntity = imageRepository.findById(imageId);
ImageEntity imageEntity = optionalImageEntity.orElseThrow(() -> new IllegalArgumentException("해당 이미지가 존재하지 않습니다. id=" + imageId));

imageRepository.deleteById(imageId);
imageService.deleteImage(imageEntity.getImageUrl());
}
}

for (MultipartFile image : images) {
String imageUrl = imageService.saveImage(image);

Expand All @@ -186,15 +197,6 @@ public void patchBoard(int boardId, String boardJson, MultipartFile[] images, St
}


if (boardUpdateDTO.getDeletedImages() != null) {
for (Integer imageId : boardUpdateDTO.getDeletedImages()) {
Optional<ImageEntity> optionalImageEntity = imageRepository.findById(imageId);
ImageEntity imageEntity = optionalImageEntity.orElseThrow(() -> new IllegalArgumentException("해당 이미지가 존재하지 않습니다. id=" + imageId));

imageRepository.deleteById(imageId);
imageService.deleteImage(imageEntity.getImageUrl());
}
}

BoardEntity boardEntity = BoardEntity.builder()
.boardId(boardId)
Expand Down
6 changes: 4 additions & 2 deletions src/main/java/com/weatherfit/board/service/ImageService.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,9 @@ public String saveImage(MultipartFile file) {
String originalFilename = file.getOriginalFilename();
String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));

// 파일 이름에 원래 이름을 사용합니다.
String fileName = originalFilename;
// UUID를 생성하고, 이를 파일 이름에 포함합니다.
String uuid = UUID.randomUUID().toString();
String fileName = uuid + "_" + originalFilename;
String fileUrl = "https://" + bucketName + ".s3.amazonaws.com/" + fileName;

if (!amazonS3Client.doesObjectExist(bucketName, fileName)) {
Expand All @@ -49,6 +50,7 @@ public String saveImage(MultipartFile file) {
throw new RuntimeException("Failed to upload image to S3", e);
}
}

public void deleteImage(String imageUrl) {
String imageName = imageUrl.substring(imageUrl.lastIndexOf("/") + 1);
amazonS3Client.deleteObject(bucketName, imageName);
Expand Down

0 comments on commit 7bc70c8

Please sign in to comment.