본문 바로가기
IT개발

[google drive] 웹 파일업로드시 파일을 구글드라이버로 올리기

by 팀모 2025. 2. 5.

1. "API 및 서비스 > 라이브러리"에서 Google Drive API 검색 후 활성화.

"API Enabled" 가 보이면 활성화된것이다.

 

2. 'Service Accounts' 에 생성한 서비스로 들어간다.

 

 

3. 서비스계정키 파일 만들기

 

4. JSON 선택후 'CREATE' 클릭

 

5. 다운로드됩니다.

 

6. 프로젝트(classpath내에) 배치

 

7. 대상 구글 드라이버에 들어가서 대상 ROOT폴더의 ID(PARENT_ID)알아내기

구글드라이버화면

 

8. 공유URL로 부터 "PARENT_FOLDER_ID or Dir or Folder" 추출

 

9. GoogleDriveService.java 에서 구글드라이버 oauth2인증을 위한 필수 정보를 세팅한다.

private static final String SERVICE_ACCOUNT_JSON = "/jjtmaster-c4643b05a0b8.json"; // `resources` 폴더에 저장

private static final String PARENT_FOLDER_ID = "1GdVDvDM5xt1xpoJFF5IPSX45abf5eLPn"; // 대표 Google Drive 폴더

 

10. GoogleDriveServer.java작성최종

 
package M;

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.AbstractInputStreamContent;
import com.google.api.client.http.FileContent;
import com.google.api.client.http.InputStreamContent;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.util.Collections;

@Service
public class GoogleDriveService {
    
    private static final String SERVICE_ACCOUNT_JSON = "/jjtmaster-c4643b05a0b8.json"; // `resources` 폴더에 저장
    private static final String PARENT_FOLDER_ID = "1GdVDvDM5xt1xpoJFF5IPSX45abf5eLPn"; // 대표 Google Drive 폴더 ID
    //final String dir = '1GdVDvDM5xt1xpoJFF5IPSX45abf5eLPn'; //앱코드
    
    
    private Drive getDriveService() throws IOException, GeneralSecurityException {
        InputStream in = getClass().getResourceAsStream(SERVICE_ACCOUNT_JSON);
        GoogleCredential credential = GoogleCredential.fromStream(in)
                .createScoped(Collections.singleton(DriveScopes.DRIVE_FILE));

        return new Drive.Builder(credential.getTransport(), credential.getJsonFactory(), credential)
                .setApplicationName("GoogleDriveUploader")
                .build();
    }

    public String uploadFile(Resource fileResource, String mimeType) throws IOException, GeneralSecurityException {
        Drive driveService = getDriveService();

        File fileMetadata = new File();
        fileMetadata.setName(fileResource.getFilename());
        fileMetadata.setParents(Collections.singletonList(PARENT_FOLDER_ID));

        AbstractInputStreamContent fileContent = new InputStreamContent(mimeType, fileResource.getInputStream());

        File uploadedFile = driveService.files().create(fileMetadata, fileContent)
                .setFields("id")
                .execute();

        return uploadedFile.getId(); // 업로드된 파일 ID 반환
    }
}

 

 

 

11. java serviece를 개발에 필요한 모듈가져오기

가. google-api-client: Google API와의 통신을 위한 클라이언트 라이브러리입니다.
나. google-oauth-client-jetty: OAuth 2.0 인증을 처리합니다.

다. google-api-services-drive: Google Drive API의 핵심 기능을 제공합니다.

 

<dependency>
    <groupId>com.google.api-client</groupId>
    <artifactId>google-api-client</artifactId>
    <version>2.2.0</version>
</dependency>

<dependency>
    <groupId>com.google.oauth-client</groupId>
    <artifactId>google-oauth-client-jetty</artifactId>
    <version>1.34.1</version>
</dependency>

<dependency>
    <groupId>com.google.apis</groupId>
    <artifactId>google-api-services-drive</artifactId>
    <version>v3-rev20230212-2.0.0</version>
</dependency>

 

12. controller코딩예제

    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            Resource fileResource = new ByteArrayResource(file.getBytes()) {
                @Override
                public String getFilename() {
                    return file.getOriginalFilename();
                }
            };
            String fileId = googleDriveService.uploadFile(fileResource, file.getContentType());
            return ResponseEntity.ok("파일 업로드 성공! 파일 ID: " + fileId);
        } catch (IOException | GeneralSecurityException e) {
        	e.printStackTrace();
            return ResponseEntity.status(500).body("파일 업로드 실패: " + e.getMessage());
        }
    }

 

13. 화면(html)코딩예제

<input type="file" id="fileInput">
<button id="upload">upload</button>

<script>
document.getElementById("upload").onclick = async function() {
    const fileInput = document.getElementById("fileInput");
    if (!fileInput.files.length) {
        alert("파일을 선택하세요!");
        return;
    }

    const formData = new FormData();
    formData.append("file", fileInput.files[0]);

    const response = await fetch("/upload", {
        method: "POST",
        body: formData
    });

    const result = await response.text();
    alert(result);
};
</script>

 

필자는 "http://localhost:8443/googleDriveOauth.html" 이런식으로 테스트해서 성공확인하였습니다.