Spring Boot 에서 네이버 클라우드 Object Storage 에 파일 업로드

2025. 3. 3. 02:53·Spring Boot/Sprng Boot Sample Code

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
'Spring Boot/Sprng Boot Sample Code' 카테고리의 다른 글
  • [Spring Boot 3.x] 6. @ControllerAdvice를 활용한 Global Exception Handling 전역 예외 처리
  • [Spring Boot 3.x] 5. @Valid 어노테이션을 통한 DTO validation 설정
  • [SpringBoot 3.x] 4. @PreAuthorize 어노테이션을 이용한 API 인가 설정
  • [Spring Boot 3.x] 3. JWT 토큰 인증(filter) & API 테스트
Yun-seul
Yun-seul
재능이 없으면 열심히라도 하자
  • Yun-seul
    윤슬
    Yun-seul
  • 전체
    오늘
    어제
    • 분류 전체보기 (22)
      • Java (1)
        • Java 기본 (1)
      • Spring Boot (9)
        • Sprng Boot Sample Code (9)
      • Docker (1)
      • Kubernetes (7)
        • Common (3)
        • GKE(Google Kubernetes Engin.. (4)
        • EKS(Elastic Kubernetes Serv.. (0)
      • Redis (0)
      • AWS (0)
      • Git (0)
      • Reflection (1)
      • Troubleshooting (3)
      • Performance Tuning (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    SpringBoot
    djava.io.tmpdir
    rfc6750
    @value #null #어노테이션 #springboot #springioc #컨테이너
    globalexception
    쿠버네티스
    unable to create tempdir. java.io.tmpdir is set to
    jwt토큰 #로그인 #회원가입 #쿠키 #보안설정
    에러코드관리
    임시디렉토리
    커스텀익셉션
    전역예외처리
    kubernetes
    GKE
    methodargumentnotvalidexception
    필터2번
    재요청
    onceperrequestfilter
    어세스토큰
    docker
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Yun-seul
Spring Boot 에서 네이버 클라우드 Object Storage 에 파일 업로드
상단으로

티스토리툴바