파일 다운로드 및 내보내기

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

다운로드 작업
alt=media URL 매개변수가 포함된 files.get 메서드를 사용하는 Blob 파일 콘텐츠
alt=media URL 매개변수가 포함된 revisions.get 메서드를 사용하는 이전 버전의 Blob 파일 콘텐츠
webContentLink 필드를 사용하는 브라우저의 Blob 파일 콘텐츠
장기 실행 작업 중에 files.download 메서드를 사용하는 Blob 파일 콘텐츠 Google Vids 파일을 다운로드하는 유일한 방법입니다.
내보내기 작업
files.export 메서드를 사용하여 앱에서 처리할 수 있는 형식의 Google Workspace 문서 콘텐츠
exportLinks 필드를 사용하는 브라우저의 Google Workspace 문서 콘텐츠
exportLinks 필드를 사용하는 브라우저의 이전 버전 Google Workspace 문서 콘텐츠
장기 실행 작업 중에 files.download 메서드를 사용하는 Google Workspace 문서 콘텐츠

파일 콘텐츠를 다운로드하거나 내보내기 전에 사용자가 파일을 capabilities.canDownload 필드를 사용하여 files 리소스에서 다운로드할 수 있는지 확인합니다.

Blob 및 Google Workspace 파일을 비롯하여 여기에 언급된 파일 유형에 대한 설명은 파일 유형을 참고하세요.

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

Blob 파일 콘텐츠 다운로드

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

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

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

Apps Script

/**
 * Downloads a file from Drive.
 * @param {string} fileId The ID of the file to download.
 * @return {Blob} The file content as a Blob.
 */
function downloadFile(fileId) {
  var url = 'https://www.googleapis.com/drive/v3/files/' + fileId + '?alt=media';
  var response = UrlFetchApp.fetch(url, {
    headers: {
      'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()
    }
  });
  return response.getBlob();
}

자바

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/snippets/drive-v3/file_snippet/download_file.py
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
import {GoogleAuth} from 'google-auth-library';
import {google} from 'googleapis';

/**
 * Downloads a file from Google Drive.
 * @param {string} fileId The ID of the file to download.
 * @return {Promise<number>} The status of the download.
 */
async function downloadFile(fileId) {
  // Authenticate with Google and get an authorized client.
  // TODO (developer): Use an appropriate auth mechanism for your app.
  const auth = new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/drive',
  });

  // Create a new Drive API client (v3).
  const service = google.drive({version: 'v3', auth});

  // Download the file.
  const file = await service.files.get({
    fileId,
    alt: 'media',
  });

  // Print the status of the download.
  console.log(file.status);
  return file.status;
}

PHP

drive/snippets/drive_v3/src/DriveDownloadFile.php
<?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;
        }
    }
}

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

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

'내 드라이브' 파일에 대한 owner 권한 또는 organizer 공유 드라이브 파일에 대한 권한이 있는 사용자는 DownloadRestrictionsMetadata 객체를 통해 다운로드를 제한할 수 있습니다. 자세한 내용은 사용자가 파일을 다운로드, 인쇄 또는 복사하지 못하도록 방지를 참고하세요.

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

부분 다운로드

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

Range: bytes=500-999

이전 버전의 Blob 파일 콘텐츠 다운로드

'영구 보관'으로 표시된 Blob 파일 콘텐츠 버전만 다운로드할 수 있습니다. 버전을 다운로드하려면 먼저 '영구 보관'으로 설정하세요. 자세한 내용은 자동 삭제에서 저장할 버전 지정을 참고하세요.

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

요청 프로토콜이 여기에 표시됩니다.

GET https://www.googleapis.com/drive/v3/files/{FILE_ID}/revisions/{REVISION_ID}?alt=media

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

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

장기 실행 작업 중에 Blob 파일 콘텐츠 다운로드

장기 실행 작업 중에 Blob 파일 콘텐츠를 다운로드하려면 다운로드할 파일의 ID가 포함된 files.download 메서드를 사용합니다. 선택적으로 버전 ID를 설정할 수 있습니다.

Google Vids 파일을 다운로드하는 유일한 방법입니다. Google Vids 파일을 내보내려고 하면 fileNotExportable 오류가 발생합니다. 자세한 내용은 장기 실행 작업 관리를 참고하세요.

Google Workspace 문서 콘텐츠 내보내기

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

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

Apps Script

/**
 * Exports a Google Workspace document.
 * @param {string} fileId The ID of the file to export.
 * @param {string} mimeType The MIME type to export to.
 * @return {Blob} The exported content as a Blob.
 */
function exportPdf(fileId, mimeType) {
  var url = 'https://www.googleapis.com/drive/v3/files/' + fileId + '/export?mimeType=' + encodeURIComponent(mimeType);
  var response = UrlFetchApp.fetch(url, {
    headers: {
      'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()
    }
  });
  return response.getBlob();
}

자바

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
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
import {GoogleAuth} from 'google-auth-library';
import {google} from 'googleapis';

/**
 * Exports a Google Doc as a PDF.
 * @param {string} fileId The ID of the file to export.
 * @return {Promise<number>} The status of the export request.
 */
async function exportPdf(fileId) {
  // Authenticate with Google and get an authorized client.
  // TODO (developer): Use an appropriate auth mechanism for your app.
  const auth = new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/drive',
  });

  // Create a new Drive API client (v3).
  const service = google.drive({version: 'v3', auth});

  // Export the file as a PDF.
  const result = await service.files.export({
    fileId,
    mimeType: 'application/pdf',
  });

  // Print the status of the export.
  console.log(result.status);
  return result.status;
}

PHP

drive/snippets/drive_v3/src/DriveExportPdf.php
<?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 범위에 대한 자세한 내용은 Google Drive API 범위 선택하기를 참고하세요.

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

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

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

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

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

장기 실행 작업 중에 Google Workspace 문서 콘텐츠 내보내기

장기 실행 작업 중에 Google Workspace 문서 콘텐츠를 내보내려면 files.download 메서드를 사용하여 다운로드할 파일의 ID와 버전 ID를 지정합니다. 자세한 내용은 장기 실행 작업 관리를 참고하세요.

파일 공유 방식 제한하기