구글doc API 연동

BACK-END 2025. 6. 5. 17:47

1. Google API 설정

  google Drive API 활성화 방법

✅ 1. Google Drive API 활성화 방법
① Google Cloud Console 접속
→ 로그인 후 우측 상단에서 프로젝트 선택 or 새로 만들기

② API 및 서비스 > 라이브러리
→ Drive 검색
→ Google Drive API 클릭
→ [사용] 버튼 클릭

③ 사용자 인증 정보 (Credentials) 이동
→ 좌측 메뉴에서 “사용자 인증 정보” 클릭

✅ 2. OAuth 2.0 Client ID 또는 Service Account 발급
🔹 A. Service Account 발급 (서버 to 서버 방식, 권장)
1. “사용자 인증 정보 만들기” > 서비스 계정 선택
이름: drive-api-access

역할: 필요 없으면 “없음”으로 두어도 됨

2. 완료 후, 해당 서비스 계정 클릭
→ “키” 탭 > 새 키 만들기 > JSON 선택 → 자동 다운로드

3. 생성된 서비스 계정 이메일 확인
→ 예: drive-api-access@your-project-id.iam.gserviceaccount.com

4. Google Drive에 폴더 생성 후, 해당 서비스 계정을 공유자로 추가
Google Drive 웹에서 해당 폴더에 대해
공유 > drive-api-access@... 이메일 입력 후 편집자 권한 부여

이 폴더 아래의 하위 폴더 및 파일 생성 가능

🔹 B. OAuth 2.0 Client ID 발급 (사용자 인증 방식)
1. “사용자 인증 정보 만들기” > OAuth 클라이언트 ID 선택
→ 먼저 OAuth 동의 화면 설정 필요

⬇️ OAuth 동의 화면 설정
사용자 유형: 일반적으로 내부 (회사 내부용이면) or 외부

앱 이름, 지원 이메일 등 기본 정보 입력

범위 설정: 아래만 추가

plaintext
복사
편집
https://www.googleapis.com/auth/drive.file
✅ drive.file: 사용자의 Google Drive에서 앱이 만든 파일만 읽고 쓰기 가능
→ 꼭 필요한 최소 권한

⬇️ 클라이언트 ID 생성
애플리케이션 유형: 일반적으로 "웹 애플리케이션" 또는 "데스크톱 앱"

이름 입력 후 생성 → 클라이언트 ID / 클라이언트 비밀 확인 가능






2. 의존성 추가 (build.gradle)

implementation 'com.google.api-client:google-api-client:2.3.0'
implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1'
implementation 'com.google.apis:google-api-services-drive:v3-rev20230825-2.0.0'

✅ 예제 코드

java
 
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;
import com.google.api.client.http.FileContent;

import java.io.IOException;
import java.util.Collections;

public class GoogleDriveUploader {

    private final Drive driveService;

    public GoogleDriveUploader() throws IOException {
        GoogleCredential credential = GoogleCredential.fromStream(
                getClass().getResourceAsStream("/your-service-account-key.json"))
                .createScoped(Collections.singleton(DriveScopes.DRIVE_FILE));

        driveService = new Drive.Builder(
                credential.getTransport(),
                credential.getJsonFactory(),
                credential
        ).setApplicationName("YourAppName").build();
    }

    /**
     * 특정 부모 폴더 아래에 새 폴더 생성
     */
    public String createSubFolder(String folderName, String parentFolderId) throws IOException {
        File fileMetadata = new File();
        fileMetadata.setName(folderName);
        fileMetadata.setMimeType("application/vnd.google-apps.folder");

        if (parentFolderId != null) {
            fileMetadata.setParents(Collections.singletonList(parentFolderId));
        }

        File folder = driveService.files().create(fileMetadata)
                .setFields("id")
                .execute();

        return folder.getId();
    }

    /**
     * 파일 업로드
     */
    public String uploadFileToFolder(java.io.File uploadFile, String folderId) throws IOException {
        File fileMetadata = new File();
        fileMetadata.setName(uploadFile.getName());
        fileMetadata.setParents(Collections.singletonList(folderId));

        FileContent mediaContent = new FileContent("application/octet-stream", uploadFile);

        File file = driveService.files().create(fileMetadata, mediaContent)
                .setFields("id")
                .execute();

        return file.getId();
    }
}

✅ 사용 예시

java
 
public class DriveTest {
    public static void main(String[] args) throws Exception {
        GoogleDriveUploader uploader = new GoogleDriveUploader();

        // 상위 폴더 ID (Google Drive에서 미리 만들어두거나 루트 폴더 ID 사용)
        String parentFolderId = "1XyzABCdefg1234567890";  // 예시

        // 1. 하위 폴더 생성
        String newFolderId = uploader.createSubFolder("새로운하위폴더", parentFolderId);

        // 2. 해당 폴더에 파일 업로드
        java.io.File file = new java.io.File("C:/temp/sample.txt");
        uploader.uploadFileToFolder(file, newFolderId);

        System.out.println("업로드 완료!");
    }
}

🔐 주의 사항

  • 서비스 계정 사용 시, 해당 계정 이메일을 드라이브 공유 권한에 추가해야 업로드 가능
  • 일반 사용자 OAuth 인증을 쓰려면 별도 토큰 플로우 필요
Posted by yongary
,