파일 다운로드 및 내보내기

Google Drive API는 다음과 같이 여러 유형의 다운로드 및 내보내기 작업을 지원합니다. 다음 표에 나와 있습니다.

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

파일 콘텐츠를 다운로드하거나 내보내기 전에 사용자가 capabilities.canDownload 필드를 사용하여 files 리소스

이 가이드의 나머지 부분에서는 이러한 유형의 광고를 실행하는 방법에 대해 자세히 설명합니다. 다운로드 및 내보내기 작업을 간편히 수행할 수 있습니다

blob 파일 콘텐츠 다운로드

Drive에 저장된 blob 파일을 다운로드하려면 다운로드할 파일의 ID와 함께 files.get 메서드를 사용합니다. 및 alt=media URL 매개변수가 포함됩니다. 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/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 매개변수를 추가하는 라이브러리 메서드를 사용합니다. 전달할 수 있습니다

앱에서 시작된 파일 다운로드는 파일 콘텐츠에 대한 읽기 액세스 권한입니다. 예를 들어 drive.readonly.metadata 범위에 파일 콘텐츠를 다운로드할 권한이 없습니다. 이 코드 샘플은 사용자가 모든 Drive 파일을 보고 관리합니다. 자세히 알아보려면 Drive 범위는 Google Drive API 선택하기 참고 범위를 참조하세요.

수정 권한이 있는 사용자는 다음을 통해 읽기 전용 사용자의 다운로드를 제한할 수 있습니다. copyRequiresWriterPermission 설정 중 필드를 false로 변경합니다.

확인된 파일 악성 파일 소유자만 다운로드할 수 있습니다. 또한 get 쿼리 매개변수 acknowledgeAbuse=true가 포함되어야 합니다. 사용자가 다운로드 위험을 인지했음을 나타내도록 악성 소프트웨어 또는 기타 악성 파일을 포함할 수 있습니다 애플리케이션은 대화형 방식으로 사용자에게 경고 메시지를 표시합니다.

일부 다운로드

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

Range: bytes=500-999

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

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

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

Drive에 저장된 blob 파일의 콘텐츠를 브라우저에서 직접 호스팅하는 대신 webContentLink 필드 files 리소스 사용자가 앱을 다운로드한 경우 파일 및 그 콘텐츠를 다운로드할 수 있는 링크가 있어야 합니다. 반환합니다. 사용자를 이 URL로 리디렉션하거나 클릭 가능한 URL로 제공할 수 있습니다. 링크를 클릭합니다.

Google Workspace 문서 콘텐츠 내보내기

Google Workspace 문서 바이트 콘텐츠를 내보내려면 내보낼 파일의 ID와 함께 files.export 메서드를 사용합니다. 올바른 MIME 유형을 사용해야 합니다. 내보내기 완료 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
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 문서 콘텐츠를 내보내려면 다음을 사용하세요. exportLinks 필드 files 리소스 문서에 따라 파일 및 그 콘텐츠를 다운로드하기 위한 링크가 모든 MIME에 대해 반환됩니다. 사용할 수 있습니다. 사용자를 URL로 리디렉션하거나 클릭합니다.

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

Google Workspace 문서 콘텐츠를 브라우저에서 revisions.get 메서드를 사용합니다. 를 다운로드할 파일의 ID와 버전의 ID로 바꿉니다. 사용자가 파일 및 그 콘텐츠를 다운로드하기 위한 링크가 있어야 합니다. 반환합니다. 사용자를 이 URL로 리디렉션하거나 클릭 가능한 URL로 제공할 수 있습니다. 링크를 클릭합니다.