下載及匯出檔案

Google Drive API 支援多種下載和匯出動作,如下表所示:

下載動作
使用 files.get 方法搭配 alt=media 網址參數的 Blob 檔案內容。
使用 revisions.get 方法和 alt=media 網址參數,取得舊版 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 檔案,請使用 files.get 方法,並提供要下載的檔案 ID 和 alt=media 網址參數。alt=media 網址參數會告知伺服器,要求以替代回應格式下載內容。

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

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 網址參數新增至基礎 HTTP 要求。

從應用程式開始下載檔案時,必須使用允許讀取檔案內容的範圍授權。舉例來說,使用 drive.readonly.metadata 範圍的應用程式無權下載檔案內容。這個程式碼範例使用受限的「drive」檔案範圍,可讓使用者查看及管理所有雲端硬碟檔案。如要進一步瞭解雲端硬碟範圍,請參閱「選擇 Google Drive API 範圍」。

擁有owner權限 (適用於「我的雲端硬碟」檔案) 或organizer權限 (適用於共用雲端硬碟檔案) 的使用者,可以透過 DownloadRestrictionsMetadata 物件限制下載。詳情請參閱「禁止使用者下載、列印或複製你的檔案」。

如果檔案被判定為濫用 (例如有害軟體),只有檔案擁有者可以下載。 此外,您必須加入 get 查詢參數 acknowledgeAbuse=true,指出使用者已瞭解下載潛在有害軟體或其他濫用檔案的風險。應用程式應先以互動方式警告使用者,再使用這個查詢參數。

部分下載

部分下載是指只下載檔案的指定部分。您可以使用 Range 標頭搭配位元組範圍,指定要下載的檔案部分。例如:

Range: bytes=500-999

下載舊版 Blob 檔案內容

您只能下載標示為「永久保存」的 Blob 檔案內容修訂版本。 如要下載修訂版本,請先將其設為「永久保存」。 詳情請參閱「指定要從自動刪除作業中排除的修訂版本」。

如要下載舊版 Blob 檔案的內容,請使用 revisions.get 方法,並提供要下載的檔案 ID、修訂版本 ID 和 alt=media 網址參數。alt=media 網址參數會告知伺服器,要求下載內容做為替代回應格式。與 files.get 類似,revisions.get 方法也會接受選用的查詢參數 acknowledgeAbuseRange 標頭。詳情請參閱「管理長時間執行的作業」。

要求通訊協定如下所示。

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

在瀏覽器中下載 Blob 檔案內容

如要在瀏覽器中下載儲存在雲端硬碟的 Blob 檔案內容 (而非透過 API),請使用 files 資源的 webContentLink 欄位。如果使用者有權下載檔案,系統會傳回下載檔案和內容的連結。您可以將使用者重新導向至這個網址,或提供可點選的連結。

在長時間執行的作業期間下載 Blob 檔案內容

如要在長時間執行的作業期間下載 Blob 檔案內容,請使用 files.download 方法,並提供要下載的檔案 ID。您可以選擇設定修訂版本的 ID。這是下載 Google Vids 檔案的唯一方法。詳情請參閱「管理長時間執行的作業」。

匯出 Google Workspace 文件內容

如要匯出 Google Workspace 文件的位元組內容,請使用 files.export 方法,並提供要匯出的檔案 ID 和正確的 MIME 類型。匯出的內容大小上限為 10 MB。

下列程式碼範例說明如何使用 files.export 方法,透過 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。如需各項 Google Workspace 文件支援的所有匯出 MIME 類型完整清單,請參閱「Google Workspace 文件匯出 MIME 類型」。

在瀏覽器中匯出 Google Workspace 文件內容

如要在瀏覽器中匯出 Google Workspace 文件內容,請使用 files 資源的 exportLinks 欄位。系統會根據文件類型,傳回每個可用 MIME 類型的檔案和內容下載連結。您可以將使用者重新導向至網址,或提供可點選的連結。

在瀏覽器中匯出舊版 Google Workspace 文件的內容

如要在瀏覽器中匯出 Google Workspace 文件的舊版內容,請使用 revisions.get 方法,並提供要下載的檔案 ID 和修訂版本 ID,產生匯出連結,然後透過該連結執行下載作業。如果使用者有檔案的下載權限,系統就會傳回下載檔案和內容的連結。您可以將使用者重新導向至這個網址,或提供可點選的連結。

在長時間執行的作業期間匯出 Google Workspace 文件內容

如要在長時間執行的作業期間匯出 Google Workspace 文件內容,請使用 files.download 方法,並提供要下載的檔案 ID 和修訂版本 ID。詳情請參閱管理長時間執行的作業

限制檔案共用方式