파일 다운로드 및 내보내기

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

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

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

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

blob 파일 콘텐츠 다운로드

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

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

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

Java

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
/**
 * 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' 파일 범위를 사용합니다. 드라이브 범위에 대한 자세한 내용은 Google 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를 사용하는 대신 브라우저 내에서 드라이브에 저장된 blob 파일의 콘텐츠를 다운로드하려면 files 리소스의 webContentLink 필드를 사용합니다. 사용자에게 파일 다운로드 액세스 권한이 있으면 파일 및 파일 콘텐츠를 다운로드할 수 있는 링크가 반환됩니다. 사용자를 이 URL로 리디렉션하거나 클릭 가능한 링크로 제공할 수 있습니다.

Google Workspace 문서 콘텐츠 내보내기

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

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

Java

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
/**
 * 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 범위를 사용합니다. 드라이브 범위에 대한 자세한 내용은 Google 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로 리디렉션하거나 클릭 가능한 링크로 제공할 수 있습니다.