본문 바로가기

Spring Boot

[SpringBoot] 구글드라이브 파일 다운로드 구현

반응형

https://neosm.tistory.com/entry/SpringBoot-%EA%B5%AC%EA%B8%80%EB%93%9C%EB%9D%BC%EC%9D%B4%EB%B8%8C-%ED%8C%8C%EC%9D%BC%EB%A6%AC%EC%8A%A4%ED%8A%B8-%EC%B7%A8%EB%93%9D

 

[SpringBoot] 구글드라이브 파일리스트 취득

Google Drive API의 files().list() 메소드를 호출하여 파일 목록을 가져옵니다. 결과로 반환된 FileList 객체에서 파일 목록을 가져와서 각 파일의 이름과 ID를 출력합니다. import com.google.api.client.auth.oauth2.C

neosm.tistory.com

위 내용에서 Drive driveService, String fileId, String fileName 취득

import com.google.api.client.http.ByteArrayContent;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.model.File;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Service
public class GoogleDriveService {

    public void downloadFile(Drive driveService, String fileId, String fileName) throws IOException {
        File file = driveService.files().get(fileId).execute();
        ByteArrayContent content = (ByteArrayContent) driveService.files().get(fileId).executeMediaAsInputStream();
        Path path = Paths.get(fileName);
        Files.write(path, content.getByteArray());
    }
}

Google Drive API의 files().get(fileId) 메소드를 호출하여 파일을 가져옵니다. 그리고 가져온 파일을 ByteArrayContent 객체에 쓰고, 그것을 파일로 저장합니다. 파일의 저장 경로는 fileName 매개변수로 지정할 수 있습니다.

반응형