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

Google Drive API は、以下のような数種類のダウンロードおよびエクスポート操作をサポートしています。 次の表に示すリストをご覧ください。

オフライン
alt=media URL パラメータとともに files.get メソッドを使用する blob ファイルのコンテンツ。
alt=media URL パラメータで revisions.get メソッドを使用する、以前のバージョンの blob ファイルのコンテンツ。
ブラウザでの blob ファイルの内容(webContentLink フィールドを使用)。
エクスポート
files.export を使用して、アプリが処理できる形式Google Workspace ドキュメントのコンテンツをドキュメント化します。
ブラウザで exportLinks フィールドを使用する Google Workspace ドキュメントのコンテンツ。
以前のバージョンの Google Workspace ドキュメントのコンテンツを表示するには、ブラウザで exportLinks フィールドを使用します。

ファイル コンテンツをダウンロードまたはエクスポートする前に、ユーザーが Cloud Storage バケットの capabilities.canDownload フィールドを使用して、 files リソース。

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

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

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

alt=media URL パラメータはシステム パラメータ 利用できます。クライアント ライブラリを このパラメータを明示的に設定する必要はありません。

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

PHP

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 スコープには、ファイルの内容をダウンロードする権限がありません。 このコードサンプルでは、制限付きの「ドライブ」ファイル スコープを使用して、ユーザーが以下の操作を行えるようにします。 ドライブ ファイルのすべてを表示、管理できます。詳細情報 ドライブのスコープについては、Google Drive API を選択する スコープ

編集権限を持つユーザーは、読み取り専用ユーザーによるダウンロードを copyRequiresWriterPermission の設定 フィールドを false に設定します。

以下として識別されたファイル 嫌がらせ行為者 (有害なソフトウェアなど)をダウンロードできるのは、ファイルのオーナーのみです。 また、get クエリ パラメータ acknowledgeAbuse=true を含める必要があります。 ダウンロードのリスクがあることをユーザーが承認したことを示す 望ましくないソフトウェアやその他の不正なファイル。アプリケーションはインタラクティブに このクエリ パラメータを使用する前にユーザーに警告する。

部分ダウンロード

部分ダウンロードでは、ファイルの特定の部分のみをダウンロードします。マイページ ファイルの中でダウンロードするファイルの部分を byte 範囲Range ヘッダーに置き換えます。例:

Range: bytes=500-999

以前のバージョンで blob ファイルの内容をダウンロードする

以前のバージョンの blob ファイルの内容をダウンロードするには、 次の ID を持つ revisions.get メソッド ダウンロードするファイル、リビジョンの ID、alt=media URL パラメータ。 alt=media URL パラメータは、コンテンツのダウンロードが 代替レスポンス形式としてリクエストできます。files.get と同様に、 revisions.get メソッドは、省略可能なクエリ パラメータも受け入れます。 acknowledgeAbuseRange ヘッダー。Google Cloud Storage バケットの 詳しくは、ファイルのダウンロードと公開 できます

ブラウザで blob ファイルのコンテンツをダウンロードする

ドライブに保存されている blob ファイルのコンテンツを、 API ではなく webContentLink フィールド files リソース。ユーザーがダウンロードした場合 ファイルとその内容をダウンロードするためのリンクが 返されます。ユーザーをこの URL にリダイレクトするか、クリック可能な URL として提供できます。 表示されます。

Google Workspace ドキュメントのコンテンツを書き出す

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

次のコードサンプルは、files.export メソッドを使用して Cloud Storage バケットをエクスポートする方法を示しています。 Drive API クライアントを使用した PDF 形式の Google Workspace ドキュメント ライブラリ:

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;
  }
}

PHP

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 スコープを使用して、ユーザーによる閲覧と閲覧を許可する 管理する方法を学びました。詳細情報 ドライブのスコープについては、Google Drive API を選択する スコープ

このコードサンプルでは、エクスポート MIME タイプを application/pdf として宣言しています。1 つの 各 Google Workspace でサポートされているすべてのエクスポート MIME タイプの完全なリスト 詳しくは、Google Workspace の MIME タイプを書き出す ドキュメントをご覧ください

ブラウザで Google Workspace ドキュメントのコンテンツを書き出す

ブラウザ内で Google Workspace ドキュメントのコンテンツを書き出すには、 exportLinks フィールド files リソース。ドキュメントによって異なる ファイルとその内容をダウンロードするためのリンクが MIME ごとに返されます。 使用できます。ユーザーを特定の URL にリダイレクトするか、 クリック可能なリンクです

ブラウザで Google Workspace ドキュメントのコンテンツを以前のバージョンにエクスポートする

以前のバージョンの Google Workspace ドキュメントのコンテンツを revisions.get メソッドを使用します。 ダウンロードするファイルの ID とリビジョンの ID に置き換えます。ユーザーが ファイルへのダウンロード アクセス権、ファイルとその内容をダウンロードするためのリンクが 返されます。ユーザーをこの URL にリダイレクトするか、クリック可能な URL として提供できます。 表示されます。