ファイルのダウンロードとエクスポート

Google ドライブ 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 ドキュメント コンテンツ。

ファイル コンテンツをダウンロードまたはエクスポートする前に、ユーザーがファイルをダウンロードできることを 、files リソースの capabilities.canDownload フィールドを使用して確認します。

BLOB ファイルや Google Workspace ファイルなど、ここで説明するファイルタイプの詳細については、ファイルタイプをご覧ください。

このガイドの残りの部分では、これらの種類のダウンロード アクションとエクスポート アクションを実行する手順について詳しく説明します。

BLOB ファイル コンテンツをダウンロードする

ドライブに保存されている BLOB ファイルをダウンロードするには、ダウンロードするファイルの ID と alt=media URL パラメータを指定して files.get メソッドを使用します。alt=media URL パラメータは、代替レスポンス形式としてコンテンツのダウンロードがリクエストされていることをサーバーに伝えます。

alt=media URL パラメータは、システム パラメータで、すべての Google REST API で使用できます。ドライブ 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();
}

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
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 スコープを使用するアプリは、ファイル コンテンツをダウンロードする権限がありません。 このコードサンプルでは、ユーザーがすべてのドライブ ファイルを表示および管理できる、制限付きの「ドライブ」ファイル スコープを使用します。ドライブ スコープの詳細については、Google ドライブ 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 経由ではなく、ブラウザ内でドライブに保存されている BLOB ファイルのコンテンツをダウンロードするには、webContentLink フィールドの files リソースを使用します。ユーザーがファイルへのダウンロード アクセス権を持っている場合は、ファイルとそのコンテンツをダウンロードするためのリンクが返されます。この URL にユーザーをリダイレクトするか、クリック可能なリンクを提示します。

長時間実行オペレーション中に BLOB ファイル コンテンツをダウンロードする

長時間実行オペレーション中に BLOB ファイルのコンテンツをダウンロードするには、ダウンロードする ファイルの ID を指定して files.download メソッドを使用します。必要に応じて、改訂バージョンの ID を設定できます。

これは、Google Vids ファイルをダウンロードする唯一の方法です。Google Vids ファイルをエクス 101 ポートしようとすると、101fileNotExportable エラーが表示されます。101詳細については、長時間実行 オペレーションを管理するをご覧ください。

Google Workspace ドキュメント コンテンツをエクスポートする

Google Workspace ドキュメントのバイト コンテンツをエクスポートするには、エクスポートするファイルの ID と 正しい MIME タイプを指定して files.export メソッドを使用します。エクスポートされるコンテンツは 10 MB に制限されます。

次のコードサンプルは、ドライブ 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();
}

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
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 スコープを使用します。ドライブ スコープの詳細については、Google ドライブ 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 を指定して使用します。詳細については、 長時間実行オペレーションを管理するをご覧ください。

ファイルの共有方法を制限する