build.gradle

implementation 'org.springframework.cloud:spring-cloud-starter-aws:2.2.6.RELEASE'

application.yml

spring:
  servlet:
    multipart:
      max-file-size: 10MB
      max-request-size: 10MB
cloud:
  aws:
    credentials:
      access-key: ${s3_access_key}
      secret-key: ${s3_secret_key}
    region:
      static: ${s3_region}
    s3:
      bucket: ${s3_bucket}
    stack:
      auto: false

git에 절대로 access-key, secret-key 이 두개가 올라가면 안된다!!!!!


S3Config

@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 AmazonS3 amazonS3Client() {
        AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);

        return AmazonS3ClientBuilder
                .standard()
                .withCredentials(new AWSStaticCredentialsProvider(credentials))
                .withRegion(region)
                .build();
    }
}

AwsS3UploadService


@Component
@RequiredArgsConstructor

public class AwsS3UploadService implements UploadService {

    private final AmazonS3 amazonS3;
    private final S3Component component;

    @Override
    public  void  uploadFile(InputStream inputStream, ObjectMetadata objectMeTadata, String fileName){
        amazonS3.putObject(new PutObjectRequest(component.getBucket() +"/test" ,fileName,inputStream,objectMeTadata).withCannedAcl(CannedAccessControlList.PublicRead));
    }

    @Override
    public  String getFileUrl(String fileName){
        return amazonS3.getUrl(component.getBucket(),fileName).toString();
    }
}

FileuploadController


@RequiredArgsConstructor
@RestController
public class FileuploadController {
    private final FileUploadService fileUploadService;

    @PostMapping("/api/v1/upload")
    public String uploadImage(@RequestParam (value ="file", required=false) MultipartFile file) throws IllegalAccessException {
        return fileUploadService.uploadImage(file);
    }
}

FileUploadService

@RequiredArgsConstructor
@Service
public class FileUploadService {

    private final UploadService s3Service;

    //Multipart를 통해 전송된 파일을 업로드하는 메소드
    public String uploadImage(MultipartFile file) throws IllegalAccessException {
        String fileName = createFileName(file.getOriginalFilename());
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentLength(file.getSize());
        objectMetadata.setContentType(file.getContentType());
        try (InputStream inputStream = file.getInputStream()) {
            s3Service.uploadFile(inputStream, objectMetadata, fileName);
        } catch(IOException e) {
            throw new IllegalAccessException(String.format("파일 변환 중에러가 발생하였습니다.(%s)", file.getOriginalFilename()));
        }
        return s3Service.getFileUrl(fileName);
    }

    //기존 확장자명을 유지한 채, 유니크한 파일의 이름을 생성하는 로직
    private String createFileName(String originalFileName) throws IllegalAccessException {
        return UUID.randomUUID().toString().concat(getFileExtension(originalFileName));
    }

    //파일의 확장자명을 가져오는 로직
    private String getFileExtension(String fileName) throws IllegalAccessException {
        try {
            return fileName.substring(fileName.lastIndexOf(".") + 1);
        } catch (StringIndexOutOfBoundsException e) {
            throw new IllegalAccessException(String.format("잘못된 형식의 파일($s) 입니다", fileName));
        }
    }
}

S3Component


@Getter
@Setter
@ConfigurationProperties(prefix= "cloud.aws.s3")
@Component
public class S3Component {

    private String bucket;

}

UploadService


public interface UploadService {
    void uploadFile(InputStream inputStream, ObjectMetadata objectMetadata, String fileName);

    String getFileUrl(String fileName);
}


profile
개발자몽

0개의 댓글

Powered by GraphCDN, the GraphQL CDN