1. 네이버 클라우드 플랫폼에서 Object Storage 이용신청
처음 가입해 결제정보를 등록하면 10만원에 해당하는 크래딧을 주기 때문에 테스트 용도로는 추가적인 결제 없이 충분히 활용 가능하다.
https://www.ncloud.com/product/storage/objectStorage
네이버 클라우드 플랫폼 Naver Cloud Flatform -> 서비스 -> Storage -> Object Storage
2. 버킷 생성
https://console.ncloud.com/objectStorage/objectStorageList
메인페이지 -> 콘솔 -> Object Storage -> Bucket Management -> 버킷생성
3. 인증키 생성
마이페이지 -> 계정관리 -> 인증키 관리 -> 신큐 API 인증키 생성 -> 발급받은 Access Key ID, Secret Key 를 환경 변수에 추가
4. build.gradle 에 의존성 추가
build.gradle
implementation 'software.amazon.awssdk:s3:2.20.50
5. 환경변수 설정
application-ncp.yml
ncp:
access-key : ${NCP_ACCESS_KEY}
secret-key : ${NCP_SECRET_KEY}
bucket-name : ${NCP_BUCKET_NAME}
6. 네이버 클라우드와 통신을 위한 클라이언트 설정 (config 클래스)
NcpStorageConfig.java
@Configuration
public class NcpStorageConfig {
@Value("${ncp.access-key}")
private String accessKey;
@Value("${ncp.secret-key}")
private String secretKey;
@Bean
public S3Client s3Client() {
return S3Client.builder()
.region(Region.of("kr-standard")) // 네이버 클라우드는 "kr-standard" 사용
.credentialsProvider(StaticCredentialsProvider.create(
AwsBasicCredentials.create(accessKey, secretKey)
))
.endpointOverride(URI.create("https://kr.object.ncloudstorage.com"))
.build();
}
}
7. 업로드 및 다운로드를 위한 컨트롤러 작성
NcpStorageController
@RestController
@RequestMapping("/api/v1/files")
public class NcpStorageController {
private final NcpStorageService ncpStorageService;
public NcpStorageController(NcpStorageService ncpStorageService) {
this.ncpStorageService = ncpStorageService;
}
@PostMapping("/upload")
public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
String fileUrl = ncpStorageService.uploadFile(file);
return ResponseEntity.ok(fileUrl);
}
@GetMapping("/download/{fileName}")
public ResponseEntity<Resource> downloadFile(@PathVariable String fileName) {
// 네이버 클라우드에서 파일 다운로드 URL을 가져오는 서비스 호출
byte[] data = ncpStorageService.downloadFile(fileName);
ByteArrayResource resource = new ByteArrayResource(data);
// 응답에 파일 데이터와 메타정보 설정
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName)
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.contentLength(data.length)
.body(resource);
}
}
8. 업로드 및 다운로드를 위한 서비스 클래스 작성
NcpStorageService
@Service
public class NcpStorageService {
private final S3Client s3Client;
@Value("${ncp.bucket-name}")
private String bucketName;
public NcpStorageService(S3Client s3Client) {
this.s3Client = s3Client;
}
public String uploadFile(MultipartFile file) {
try {
String fileName = file.getOriginalFilename();
// S3 업로드 요청 생성
PutObjectRequest putObjectRequest = PutObjectRequest.builder()
.bucket(bucketName)
.key(fileName)
.contentType(file.getContentType())
.build();
// 파일 업로드 실행
s3Client.putObject(putObjectRequest, RequestBody.fromBytes(file.getBytes()));
// 업로드된 파일의 URL 반환
return "https://kr.object.ncloudstorage.com/" + bucketName + "/" + fileName;
} catch (IOException e) {
throw new RuntimeException("파일 업로드 실패", e);
}
}
public byte[] downloadFile(String fileName) {
GetObjectRequest getObjectRequest = GetObjectRequest.builder()
.bucket(bucketName) // 버킷 이름
.key(fileName) // 다운로드할 파일 이름
.build();
// 파일을 다운로드하고 byte[]로 반환
return s3Client.getObject(getObjectRequest, ResponseTransformer.toBytes()).asByteArray();
}
}
9. 테스트
포스트맨에서 메서드는 POST, Body 타입은 form-data로 설정해 key값은 filename (File) 로 설정하고 Value에서 로컬에 있는 파일을 선택후 Send하면 업로드 할 수 있다.
GET 메서드로 요청시 Save Response 옆 점 3개를 누르면 .Save response to file 이라는 버튼이 나온다.
해당 버튼을 클릭시 파일을 다운로드 할 수 있다.
'Spring Boot > Sprng Boot Sample Code' 카테고리의 다른 글
[Spring Boot 3.x] 6. @ControllerAdvice를 활용한 Global Exception Handling 전역 예외 처리 (0) | 2025.03.03 |
---|---|
[Spring Boot 3.x] 5. @Valid 어노테이션을 통한 DTO validation 설정 (0) | 2025.03.03 |
[SpringBoot 3.x] 4. @PreAuthorize 어노테이션을 이용한 API 인가 설정 (0) | 2025.03.03 |
[Spring Boot 3.x] 3. JWT 토큰 인증(filter) & API 테스트 (0) | 2025.03.01 |
[Spring Boot 3.x] 2. JWT 토큰과 쿠키를 이용한 로그인 구현 (0) | 2025.02.24 |