Skip to content

Commit

Permalink
[refactor] #101- S3 관련 기능을 공통 유틸로 추출
Browse files Browse the repository at this point in the history
  • Loading branch information
soljjang777 committed Nov 17, 2024
1 parent 3b01498 commit 05fe7af
Show file tree
Hide file tree
Showing 3 changed files with 80 additions and 29 deletions.
38 changes: 9 additions & 29 deletions src/main/java/com/wooribound/domain/resume/ResumeServiceImpl.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
package com.wooribound.domain.resume;

import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.DeleteObjectRequest;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.wooribound.domain.resume.dto.ResumeDTO;
import com.wooribound.domain.resume.dto.ResumeDetailDTO;
import com.wooribound.domain.wbuser.WbUser;
Expand All @@ -11,17 +9,15 @@
import com.wooribound.domain.workhistory.WorkHistoryRepository;
import com.wooribound.global.exception.NotEntityException;
import com.wooribound.global.util.AuthenticateUtil;
import com.wooribound.global.util.S3Util;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;
Expand All @@ -30,10 +26,10 @@
@Service
public class ResumeServiceImpl implements ResumeService {

@Value("${cloud.aws.s3.bucketName}")
private String bucket;
@Value("${aws.s3.wbUser.folder}")
String wbUserFolderName;

private final AmazonS3Client amazonS3Client;
private final S3Util s3Util;
private final AuthenticateUtil authenticateUtil;
private final ResumeRepository resumeRepository;
private final WbUserRepository wbUserRepository;
Expand Down Expand Up @@ -77,29 +73,22 @@ public ResumeDTO registerResume(Authentication authentication, MultipartFile use
String userId = authenticateUtil.CheckWbUserAuthAndGetUserId(authentication);

Optional<WbUser> byIdWbUser = wbUserRepository.findById(userId);

if (byIdWbUser.isEmpty()) {
throw new NotEntityException();
}

long resumeId = 1L;
Optional<Long> maxResumeId = resumeRepository.getMaxResumeId();

if (maxResumeId.isPresent()) {
resumeId = maxResumeId.get() + 1;
}

String uploadFileName = createFileName(userImg.getOriginalFilename());

ObjectMetadata metadata= new ObjectMetadata();
metadata.setContentType(userImg.getContentType());
metadata.setContentLength(userImg.getSize());
amazonS3Client.putObject(bucket,uploadFileName,userImg.getInputStream(),metadata);
String fileURL = s3Util.uploadFile(userImg, wbUserFolderName);

Resume resume = Resume.builder()
.resumeId(resumeId)
.wbUser(byIdWbUser.get())
.userImg(amazonS3Client.getUrl(bucket, uploadFileName).toString())
.userImg(fileURL)
.resumeEmail(resumeEmail)
.userIntro(userIntro)
.build();
Expand Down Expand Up @@ -135,21 +124,12 @@ public ResumeDTO updateResume(Authentication authentication, MultipartFile userI

if (userImg != null) {
// s3에서 파일 삭제
String url = byIdResume.get().getUserImg();
String encodedFileName = url.substring(url.lastIndexOf("/") + 1);
String deleteFileName = URLDecoder.decode(encodedFileName, StandardCharsets.UTF_8);

amazonS3Client.deleteObject(new DeleteObjectRequest(bucket, deleteFileName));
s3Util.deleteFile(byIdResume.get().getUserImg(), wbUserFolderName);

// s3에 새로운 파일 업로드
String uploadFileName = createFileName(userImg.getOriginalFilename());
ObjectMetadata metadata= new ObjectMetadata();
metadata.setContentType(userImg.getContentType());
metadata.setContentLength(userImg.getSize());

amazonS3Client.putObject(bucket,uploadFileName,userImg.getInputStream(),metadata);
String fileURL = s3Util.uploadFile(userImg, wbUserFolderName);

resume.setUserImg(amazonS3Client.getUrl(bucket, uploadFileName).toString());
resume.setUserImg(fileURL);
}

resume.setResumeEmail(resumeEmail);
Expand Down
69 changes: 69 additions & 0 deletions src/main/java/com/wooribound/global/util/S3Util.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package com.wooribound.global.util;

import com.amazonaws.AmazonServiceException;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.DeleteObjectRequest;
import com.amazonaws.services.s3.model.ObjectMetadata;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

@RequiredArgsConstructor
@Component
public class S3Util {

@Value("${cloud.aws.s3.bucketName}")
private String bucket;

private final AmazonS3Client amazonS3Client;

// S3에 파일 업로드
public String uploadFile(MultipartFile multipartFile, String s3FolderName) {
try {
String uploadFileName = createFileName(multipartFile.getOriginalFilename());

ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentType(multipartFile.getContentType());
metadata.setContentLength(multipartFile.getSize());

amazonS3Client.putObject(bucket + s3FolderName, uploadFileName, multipartFile.getInputStream(), metadata);

return amazonS3Client.getUrl(bucket + s3FolderName, uploadFileName).toString();

} catch (AmazonServiceException e) {
e.printStackTrace();
throw new RuntimeException("S3에 파일 업로드 중 오류가 발생했습니다", e);
} catch (SdkClientException e) {
e.printStackTrace();
throw new RuntimeException("클라이언트 오류가 S3에 업로드 중 발생했습니다", e);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("파일 입력 중 오류가 발생했습니다", e);
}

}

public void deleteFile(String fileURL, String s3FolderName) {
try {
String encodedFileName = fileURL.substring(fileURL.lastIndexOf("/") + 1);
String deleteFileName = URLDecoder.decode(encodedFileName, StandardCharsets.UTF_8);

amazonS3Client.deleteObject(new DeleteObjectRequest(bucket + s3FolderName, deleteFileName));
} catch (AmazonServiceException e) {
e.printStackTrace();
throw new RuntimeException("S3에서 파일 삭제 중 오류가 발생했습니다", e);
}
}

// 파일 이름 생성 메소드
private String createFileName(String fileName) {
return UUID.randomUUID().toString().concat(fileName);
}
}
2 changes: 2 additions & 0 deletions src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,5 @@ cloud.aws.credentials.secretKey=${AWS_SECRET_KEY}
cloud.aws.s3.bucketName=${AWS_BUCKET_NAME}
cloud.aws.region.static=${AWS_REGION}
cloud.aws.stack.auto-=false
aws.s3.wbUser.folder=${S3_WBUSER_FOLDER}
aws.s3.jobPosting.folder=${S3_JOB_POSTING_FOLDER}

0 comments on commit 05fe7af

Please sign in to comment.