Skip to content

Commit

Permalink
Merge pull request #25 from DONGA-ST-A/setting/24-aws-s3
Browse files Browse the repository at this point in the history
[Setting] AWS S3 설정
  • Loading branch information
kyeong-hyeok authored Sep 8, 2023
2 parents f983dfe + 074b4e3 commit 3316241
Show file tree
Hide file tree
Showing 4 changed files with 105 additions and 0 deletions.
2 changes: 2 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ dependencies {
implementation 'com.auth0:java-jwt:4.2.1'
// Spring Data Redis
implementation 'org.springframework.boot:spring-boot-starter-data-redis'
// AWS S3
implementation 'org.springframework.cloud:spring-cloud-starter-aws:2.2.6.RELEASE'
}

tasks.named('test') {
Expand Down
68 changes: 68 additions & 0 deletions src/main/java/com/teamA/hicardi/common/s3/FileService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package com.teamA.hicardi.common.s3;

import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.DeleteObjectRequest;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.teamA.hicardi.error.exception.custom.BusinessException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

import static com.teamA.hicardi.error.ErrorCode.INVALID_FILE_UPLOAD;

@Slf4j
@Service
@RequiredArgsConstructor
public class FileService {

private final AmazonS3Client amazonS3Client;

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

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

public String uploadFile(MultipartFile multipartFile, String imageType) {
if (multipartFile == null || multipartFile.isEmpty()) return null;

String savedFileName = getSavedFileName(multipartFile, imageType);
ObjectMetadata metadata = new ObjectMetadata();

try (InputStream inputStream = multipartFile.getInputStream()) {
amazonS3Client.putObject(bucketName, savedFileName, inputStream, metadata);
} catch (IOException e) {
log.error("Failed to upload image", e);
throw new BusinessException(INVALID_FILE_UPLOAD);
}
return getResourceUrl(savedFileName);
}

public void deleteFile(String fileUrl) {
String fileName = getFileNameFromResourceUrl(fileUrl);
amazonS3Client.deleteObject(new DeleteObjectRequest(bucketName, fileName));
}

private String getSavedFileName(MultipartFile multipartFile, String imageType) {
return String.format("%s/%s-%s",
imageType, getRandomUUID(), multipartFile.getOriginalFilename());
}

private String getRandomUUID() {
return UUID.randomUUID().toString().replace("-", "");
}

private String getResourceUrl(String savedFileName) {
return amazonS3Client.getResourceUrl(bucketName, savedFileName);
}

private String getFileNameFromResourceUrl(String fileUrl) {
return fileUrl.replace(defaultUrl + "/", "");
}
}
33 changes: 33 additions & 0 deletions src/main/java/com/teamA/hicardi/config/S3Config.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package com.teamA.hicardi.config;

import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class S3Config {

@Value("${cloud.aws.credentials.access-key}")
private String accessKey;

@Value("${cloud.aws.credentials.secret-key}")
private String secretKey;

@Value("${cloud.aws.region.static}")
private String region;

@Bean
public AmazonS3Client amazonS3Client() {
BasicAWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);

return (AmazonS3Client) AmazonS3ClientBuilder
.standard()
.withRegion(region)
.withCredentials(new AWSStaticCredentialsProvider(credentials))
.build();
}
}
2 changes: 2 additions & 0 deletions src/main/java/com/teamA/hicardi/error/ErrorCode.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,10 @@ public enum ErrorCode {
ALREADY_LOGOUT_MEMBER(BAD_REQUEST, "이미 로그아웃한 회원입니다"),
ALREADY_EXIST_EMAIL(BAD_REQUEST, "이미 존재하는 이메일입니다."),
ALREADY_EXIST_USERID(BAD_REQUEST, "이미 존재하는 아이디입니다."),
INVALID_FILE_UPLOAD(BAD_REQUEST, "파일 업로드에 실패하였습니다."),
INVALID_TOKEN(UNAUTHORIZED, "잘못된 토큰입니다.");


private final int code;
private final String message;

Expand Down

0 comments on commit 3316241

Please sign in to comment.