파일 다운로드 및 내보내기

Google Drive API는 다음 표에 나열된 여러 유형의 다운로드 및 내보내기 작업을 지원합니다.

오프라인 저장
alt=media URL 매개변수와 함께 files.get 메서드를 사용하는 blob 파일 콘텐츠
alt=media URL 매개변수와 함께 revisions.get 메서드를 사용하여 이전 버전의 blob 파일 콘텐츠.
webContentLink 필드를 사용하여 브라우저의 blob 파일 콘텐츠
내보내기
Google Workspace 문서 콘텐츠(files.export를 사용하여 앱이 처리할 수 있는 형식)
exportLinks 필드를 사용하여 브라우저의 Google Workspace 문서 콘텐츠
exportLinks 필드를 사용하여 브라우저에서 이전 버전의 Google Workspace 문서 콘텐츠를 제공합니다.

이 가이드의 나머지 부분에서는 이러한 유형의 다운로드 및 내보내기 작업을 실행하는 방법을 자세히 설명합니다.

blob 파일 콘텐츠 다운로드

Drive에 저장된 blob 파일을 다운로드하려면 다운로드할 파일의 ID 및 alt=media URL 매개변수와 함께 files.get 메서드를 사용합니다. alt=media URL 매개변수는 대체 응답 형식으로 콘텐츠 다운로드를 요청하고 있음을 서버에 알립니다.

alt=media URL 매개변수는 모든 Google REST API에서 사용할 수 있는 시스템 매개변수입니다. Drive API에 클라이언트 라이브러리를 사용하는 경우에는 이 매개변수를 명시적으로 설정할 필요가 없습니다.

다음 코드 샘플은 files.get 메서드를 사용하여 Drive API 클라이언트 라이브러리로 파일을 다운로드하는 방법을 보여줍니다.

자바

drive/snippets/drive_v3/src/main/java/DownloadFile.java
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;

/* Class to demonstrate use-case of drive's download file. */
public class DownloadFile {

  /**
   * Download a Document file in PDF format.
   *
   * @param realFileId file ID of any workspace document format file.
   * @return byte array stream if successful, {@code null} otherwise.
   * @throws IOException if service account credentials file not found.
   */
  public static ByteArrayOutputStream downloadFile(String realFileId) throws IOException {
        /* Load pre-authorized user credentials from the environment.
           TODO(developer) - See https://developers.google.com/identity for
          guides on implementing OAuth2 for your application.*/
    GoogleCredentials credentials = GoogleCredentials.getApplicationDefault()
        .createScoped(Arrays.asList(DriveScopes.DRIVE_FILE));
    HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(
        credentials);

    // Build a new authorized API client service.
    Drive service = new Drive.Builder(new NetHttpTransport(),
        GsonFactory.getDefaultInstance(),
        requestInitializer)
        .setApplicationName("Drive samples")
        .build();

    try {
      OutputStream outputStream = new ByteArrayOutputStream();

      service.files().get(realFileId)
          .executeMediaAndDownloadTo(outputStream);

      return (ByteArrayOutputStream) outputStream;
    } catch (GoogleJsonResponseException e) {
      // TODO(developer) - handle error appropriately
      System.err.println("Unable to move file: " + e.getDetails());
      throw e;
    }
  }
}

Python

드라이브/스니펫/drive-v3/file_snippet/download_file.py
from __future__ import print_function

import io

import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaIoBaseDownload


def download_file(real_file_id):
    """Downloads a file
    Args:
        real_file_id: ID of the file to download
    Returns : IO object with location.

    Load pre-authorized user credentials from the environment.
    TODO(developer) - See https://developers.google.com/identity
    for guides on implementing OAuth2 for the application.
    """
    creds, _ = google.auth.default()

    try:
        # create drive api client
        service = build('drive', 'v3', credentials=creds)

        file_id = real_file_id

        # pylint: disable=maybe-no-member
        request = service.files().get_media(fileId=file_id)
        file = io.BytesIO()
        downloader = MediaIoBaseDownload(file, request)
        done = False
        while done is False:
            status, done = downloader.next_chunk()
            print(F'Download {int(status.progress() * 100)}.')

    except HttpError as error:
        print(F'An error occurred: {error}')
        file = None

    return file.getvalue()


if __name__ == '__main__':
    download_file(real_file_id='1KuPmvGq8yoYgbfW74OENMCB5H0n_2Jm9')

Node.js

drive/snippets/drive_v3/file_snippets/download_file.js
/**
 * Downloads a file
 * @param{string} realFileId file ID
 * @return{obj} file status
 * */
async function downloadFile(realFileId) {
  // Get credentials and build service
  // TODO (developer) - Use appropriate auth mechanism for your app

  const {GoogleAuth} = require('google-auth-library');
  const {google} = require('googleapis');

  const auth = new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/drive',
  });
  const service = google.drive({version: 'v3', auth});

  fileId = realFileId;
  try {
    const file = await service.files.get({
      fileId: fileId,
      alt: 'media',
    });
    console.log(file.status);
    return file.status;
  } catch (err) {
    // TODO(developer) - Handle error
    throw err;
  }
}

2,399필리핀

drive/snippets/drive_v3/src/DriveDownloadFile.php
use Google\Client;
use Google\Service\Drive;
function downloadFile()
 {
    try {

      $client = new Client();
      $client->useApplicationDefaultCredentials();
      $client->addScope(Drive::DRIVE);
      $driveService = new Drive($client);
      $realFileId = readline("Enter File Id: ");
      $fileId = '0BwwA4oUTeiV1UVNwOHItT0xfa2M';
      $fileId = $realFileId;
      $response = $driveService->files->get($fileId, array(
          'alt' => 'media'));
      $content = $response->getBody()->getContents();
      return $content;

    } catch(Exception $e) {
      echo "Error Message: ".$e;
    }

}

.NET

drive/snippets/drive_v3/DriveV3snippets/DownloadFile.cs
using Google.Apis.Auth.OAuth2;
using Google.Apis.Download;
using Google.Apis.Drive.v3;
using Google.Apis.Services;

namespace DriveV3Snippets
{
    // Class to demonstrate use-case of drive's download file.
    public class DownloadFile
    {
        /// <summary>
        /// Download a Document file in PDF format.
        /// </summary>
        /// <param name="fileId">file ID of any workspace document format file.</param>
        /// <returns>byte array stream if successful, null otherwise.</returns>
        public static MemoryStream DriveDownloadFile(string fileId)
        {
            try
            {
                /* Load pre-authorized user credentials from the environment.
                 TODO(developer) - See https://developers.google.com/identity for 
                 guides on implementing OAuth2 for your application. */
                GoogleCredential credential = GoogleCredential
                    .GetApplicationDefault()
                    .CreateScoped(DriveService.Scope.Drive);

                // Create Drive API service.
                var service = new DriveService(new BaseClientService.Initializer
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Drive API Snippets"
                });

                var request = service.Files.Get(fileId);
                var stream = new MemoryStream();

                // Add a handler which will be notified on progress changes.
                // It will notify on each chunk download and when the
                // download is completed or failed.
                request.MediaDownloader.ProgressChanged +=
                    progress =>
                    {
                        switch (progress.Status)
                        {
                            case DownloadStatus.Downloading:
                            {
                                Console.WriteLine(progress.BytesDownloaded);
                                break;
                            }
                            case DownloadStatus.Completed:
                            {
                                Console.WriteLine("Download complete.");
                                break;
                            }
                            case DownloadStatus.Failed:
                            {
                                Console.WriteLine("Download failed.");
                                break;
                            }
                        }
                    };
                request.Download(stream);

                return stream;
            }
            catch (Exception e)
            {
                // TODO(developer) - handle error appropriately
                if (e is AggregateException)
                {
                    Console.WriteLine("Credential Not found");
                }
                else
                {
                    throw;
                }
            }
            return null;
        }
    }
}

이 코드 샘플에서는 alt=media URL 매개변수를 기본 HTTP 요청에 추가하는 라이브러리 메서드를 사용합니다.

앱에서 시작된 파일 다운로드는 파일 콘텐츠에 대한 읽기 액세스를 허용하는 범위로 승인되어야 합니다. 예를 들어 drive.readonly.metadata 범위를 사용하는 앱은 파일 콘텐츠를 다운로드할 권한이 없습니다. 이 코드 샘플은 사용자가 모든 Drive 파일을 보고 관리할 수 있도록 제한된 'drive' 파일 범위를 사용합니다. Drive 범위에 대한 자세한 내용은 API 관련 승인 및 인증 정보를 참조하세요.

수정 권한이 있는 사용자는 copyRequiresWriterPermission 필드를 false로 설정하여 읽기 전용 사용자의 다운로드를 제한할 수 있습니다.

유해한 소프트웨어와 같이 악성으로 식별된 파일은 파일 소유자만 다운로드할 수 있습니다. 또한 사용자가 원치 않는 소프트웨어 또는 기타 악성 파일을 다운로드할 위험이 있음을 나타내려면 get 쿼리 매개변수 acknowledgeAbuse=true를 포함해야 합니다. 이 쿼리 매개변수를 사용하기 전에 애플리케이션에서 사용자에게 대화식으로 경고를 표시해야 합니다.

부분 다운로드

부분 다운로드에는 파일의 지정된 부분만 다운로드됩니다. Range 헤더와 함께 바이트 범위를 사용하여 다운로드하려는 파일 부분을 지정할 수 있습니다. 예를 들면 다음과 같습니다.

Range: bytes=500-999

이전 버전에서 blob 파일 콘텐츠 다운로드

이전 버전에서 blob 파일의 콘텐츠를 다운로드하려면 다운로드할 파일의 ID, 버전의 ID, alt=media URL 매개변수와 함께 revisions.get 메서드를 사용합니다. alt=media URL 매개변수는 대체 응답 형식으로 콘텐츠 다운로드를 요청하고 있음을 서버에 알립니다. files.get와 마찬가지로 revisions.get 메서드는 선택적 쿼리 매개변수 acknowledgeAbuseRange 헤더도 허용합니다. 버전 다운로드에 관한 자세한 내용은 파일 버전 다운로드 및 게시를 참고하세요.

브라우저에서 blob 파일 콘텐츠 다운로드

API를 통하지 않고 브라우저 내에 Drive에 저장된 blob 파일의 콘텐츠를 다운로드하려면 Files 리소스의 webContentLink 필드를 사용합니다. 사용자에게 파일 다운로드 권한이 있으면 파일 및 파일 콘텐츠 다운로드 링크가 반환됩니다. 사용자를 이 URL로 리디렉션하거나 클릭 가능한 링크로 제공할 수 있습니다.

Google Workspace 문서 콘텐츠 내보내기

Google Workspace 문서 바이트 콘텐츠를 내보내려면 내보낼 파일의 ID와 올바른 MIME 유형과 함께 files.export 메서드를 사용합니다. 내보낸 콘텐츠는 10MB로 제한됩니다.

다음 코드 샘플은 files.export 메서드를 사용하여 Drive API 클라이언트 라이브러리를 사용하여 PDF 형식으로 Google Workspace 문서를 내보내는 방법을 보여줍니다.

자바

drive/snippets/drive_v3/src/main/java/ExportPdf.java
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;

/* Class to demonstrate use-case of drive's export pdf. */
public class ExportPdf {

  /**
   * Download a Document file in PDF format.
   *
   * @param realFileId file ID of any workspace document format file.
   * @return byte array stream if successful, {@code null} otherwise.
   * @throws IOException if service account credentials file not found.
   */
  public static ByteArrayOutputStream exportPdf(String realFileId) throws IOException {
    // Load pre-authorized user credentials from the environment.
    // TODO(developer) - See https://developers.google.com/identity for
    // guides on implementing OAuth2 for your application.
    GoogleCredentials credentials = GoogleCredentials.getApplicationDefault()
        .createScoped(Arrays.asList(DriveScopes.DRIVE_FILE));
    HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(
        credentials);

    // Build a new authorized API client service.
    Drive service = new Drive.Builder(new NetHttpTransport(),
        GsonFactory.getDefaultInstance(),
        requestInitializer)
        .setApplicationName("Drive samples")
        .build();

    OutputStream outputStream = new ByteArrayOutputStream();
    try {
      service.files().export(realFileId, "application/pdf")
          .executeMediaAndDownloadTo(outputStream);

      return (ByteArrayOutputStream) outputStream;
    } catch (GoogleJsonResponseException e) {
      // TODO(developer) - handle error appropriately
      System.err.println("Unable to export file: " + e.getDetails());
      throw e;
    }
  }
}

Python

drive/snippets/drive-v3/file_snippet/export_pdf.py
from __future__ import print_function

import io

import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaIoBaseDownload


def export_pdf(real_file_id):
    """Download a Document file in PDF format.
    Args:
        real_file_id : file ID of any workspace document format file
    Returns : IO object with location

    Load pre-authorized user credentials from the environment.
    TODO(developer) - See https://developers.google.com/identity
    for guides on implementing OAuth2 for the application.
    """
    creds, _ = google.auth.default()

    try:
        # create drive api client
        service = build('drive', 'v3', credentials=creds)

        file_id = real_file_id

        # pylint: disable=maybe-no-member
        request = service.files().export_media(fileId=file_id,
                                               mimeType='application/pdf')
        file = io.BytesIO()
        downloader = MediaIoBaseDownload(file, request)
        done = False
        while done is False:
            status, done = downloader.next_chunk()
            print(F'Download {int(status.progress() * 100)}.')

    except HttpError as error:
        print(F'An error occurred: {error}')
        file = None

    return file.getvalue()


if __name__ == '__main__':
    export_pdf(real_file_id='1zbp8wAyuImX91Jt9mI-CAX_1TqkBLDEDcr2WeXBbKUY')

Node.js

drive/snippets/drive_v3/file_snippets/export_pdf.js
/**
 * Download a Document file in PDF format
 * @param{string} fileId file ID
 * @return{obj} file status
 * */
async function exportPdf(fileId) {
  const {GoogleAuth} = require('google-auth-library');
  const {google} = require('googleapis');

  // Get credentials and build service
  // TODO (developer) - Use appropriate auth mechanism for your app
  const auth = new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/drive',
  });
  const service = google.drive({version: 'v3', auth});

  try {
    const result = await service.files.export({
      fileId: fileId,
      mimeType: 'application/pdf',
    });
    console.log(result.status);
    return result;
  } catch (err) {
    // TODO(developer) - Handle error
    throw err;
  }
}

2,399필리핀

drive/snippets/drive_v3/src/DriveExportPdf.php
use Google\Client;
use Google\Service\Drive;
function exportPdf()
{
    try {
        $client = new Client();
        $client->useApplicationDefaultCredentials();
        $client->addScope(Drive::DRIVE);
        $driveService = new Drive($client);
        $realFileId = readline("Enter File Id: ");
        $fileId = '1ZdR3L3qP4Bkq8noWLJHSr_iBau0DNT4Kli4SxNc2YEo';
        $fileId = $realFileId;
        $response = $driveService->files->export($fileId, 'application/pdf', array(
            'alt' => 'media'));
        $content = $response->getBody()->getContents();
        return $content;

    }  catch(Exception $e) {
         echo "Error Message: ".$e;
    }

}

.NET

drive/snippets/drive_v3/DriveV3snippets/ExportPdf.cs
using Google.Apis.Auth.OAuth2;
using Google.Apis.Download;
using Google.Apis.Drive.v3;
using Google.Apis.Services;

namespace DriveV3Snippets
{
    // Class to demonstrate use of Drive export pdf
    public class ExportPdf
    {
        /// <summary>
        /// Download a Document file in PDF format.
        /// </summary>
        /// <param name="fileId">Id of the file.</param>
        /// <returns>Byte array stream if successful, null otherwise</returns>
        public static MemoryStream DriveExportPdf(string fileId)
        {
            try
            {
                /* Load pre-authorized user credentials from the environment.
                 TODO(developer) - See https://developers.google.com/identity for 
                 guides on implementing OAuth2 for your application. */
                GoogleCredential credential = GoogleCredential.GetApplicationDefault()
                    .CreateScoped(DriveService.Scope.Drive);

                // Create Drive API service.
                var service = new DriveService(new BaseClientService.Initializer
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Drive API Snippets"
                });

                var request = service.Files.Export(fileId, "application/pdf");
                var stream = new MemoryStream();
                // Add a handler which will be notified on progress changes.
                // It will notify on each chunk download and when the
                // download is completed or failed.
                request.MediaDownloader.ProgressChanged +=
                    progress =>
                    {
                        switch (progress.Status)
                        {
                            case DownloadStatus.Downloading:
                            {
                                Console.WriteLine(progress.BytesDownloaded);
                                break;
                            }
                            case DownloadStatus.Completed:
                            {
                                Console.WriteLine("Download complete.");
                                break;
                            }
                            case DownloadStatus.Failed:
                            {
                                Console.WriteLine("Download failed.");
                                break;
                            }
                        }
                    };
                request.Download(stream);
                return stream;
            }
            catch (Exception e)
            {
                // TODO(developer) - handle error appropriately
                if (e is AggregateException)
                {
                    Console.WriteLine("Credential Not found");
                }
                else
                {
                    throw;
                }
            }
            return null;
        }
    }
}

이 코드 샘플에서는 사용자가 모든 Drive 파일을 보고 관리할 수 있는 제한된 drive 범위를 사용합니다. Drive 범위에 대한 자세한 내용은 API 관련 승인 및 인증 정보를 참조하세요.

또한 코드 샘플은 내보내기 MIME 유형을 application/pdf로 선언합니다. 각 Google Workspace 문서에서 지원되는 모든 내보내기 MIME 유형의 전체 목록은 Google Workspace 문서의 MIME 유형 내보내기를 참고하세요.

브라우저에서 Google Workspace 문서 콘텐츠 내보내기

브라우저 내에서 Google Workspace 문서 콘텐츠를 내보내려면 Files 리소스의 exportLinks 필드를 사용합니다. 문서 유형에 따라 사용 가능한 모든 MIME 유형에 파일 및 파일 콘텐츠 다운로드 링크가 반환됩니다. 사용자를 URL로 리디렉션하거나 클릭 가능한 링크로 제공할 수 있습니다.

브라우저에서 Google Workspace 문서 콘텐츠를 이전 버전으로 내보내기

브라우저 내에서 이전 버전의 Google Workspace 문서 콘텐츠를 내보내려면 다운로드할 파일 ID와 버전의 ID가 있는 revisions.get 메서드를 사용합니다. 사용자에게 파일 다운로드 권한이 있으면 파일 및 파일 콘텐츠 다운로드 링크가 반환됩니다. 사용자를 이 URL로 리디렉션하거나 클릭 가능한 링크로 제공할 수 있습니다.