下载和导出文件

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 文档内容。

在 Drive API 中,blob 文件是指存储在 Google 云端硬盘上的任何原始二进制文件(例如图片、视频和 PDF),而不是 Google Workspace 文档。它不是指 JavaScript 的 Blob 对象。如需详细了解此处提及的文件类型(包括 blob 文件和 Google Workspace 文件),请参阅文件 类型

在下载或导出文件内容之前,请验证用户是否可以使用 文件使用 capabilities.canDownload 字段在 files 资源上下载文件。

本文档的其余部分将详细说明如何执行这些类型的下载和导出操作。

下载 blob 文件内容

如需下载存储在云端硬盘上的 blob 文件,请使用 files.get 方法以及要下载的文件的 ID 和 alt system parameteralt=media 参数会告知服务器,系统正在请求下载内容,以作为替代响应格式。

alt 系统参数在所有 Google REST API 中均可用。如果您使用 Drive API 客户端库,则无需显式设置此参数,因为客户端库方法会将 alt=media 参数添加到底层 HTTP 请求中。

以下代码示例展示了如何使用 files.get 方法下载文件:

Apps 脚本

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

curl

curl -L "https://www.googleapis.com/drive/v3/files/FILE_ID?alt=media" \
  --header "Authorization: Bearer ACCESS_TOKEN" \
  --output "FILE_NAME"

替换以下内容:

  • FILE_ID:要下载的文件的 ID。
  • ACCESS_TOKEN:授予 API 访问权限的访问令牌。
  • FILE_NAME:输出文件的名称。

从应用启动的文件下载必须使用允许读取文件内容的范围进行授权。例如,使用 drive.readonly.metadata 范围的应用无权下载文件内容。 客户端库代码示例使用受限的 drive 文件范围,该范围允许用户查看和管理您的所有云端硬盘文件。如需详细了解云端硬盘范围,请参阅 选择 Google Drive API 范围

具有 owner 权限(适用于我的云端硬盘文件)或 organizer 权限(适用于共享云端硬盘文件)的用户可以通过 DownloadRestrictionsMetadata 对象限制下载。如需了解详情,请参阅禁止用户下载、打印或 复制您的文件

被标识为滥用 (例如有害软件)的文件只能由文件所有者下载。 此外,acknowledgeAbuse 查询参数必须设置为 true,以表明用户已确认下载潜在垃圾软件或其他滥用文件的风险。您的应用应在使用此查询参数之前以交互方式警告用户。

访问内存中的文件数据

如果您的应用必须直接在内存中(例如作为字节缓冲区)访问文件数据,而不是将其保存到本地磁盘,则可以调整客户端库请求或处理返回的流:

  • Node.js:默认情况下,Node.js 客户端库会将文件内容 作为 Readable 流返回。如需将文件保存到本地磁盘,请执行以下操作:

    const fs = require('fs');
    
    const dest = fs.createWriteStream('/path/to/dest/file.ext');
    const response = await service.files.get(
      { fileId, alt: 'media' },
      { responseType: 'stream' }
    );
    response.data
      .on('end', () => {
        console.log('Download complete.');
      })
      .on('error', (err) => {
        console.error('Error downloading file.', err);
      })
      .pipe(dest);
    

    或者,如需直接在内存中将数据作为 ArrayBuffer 而不是流返回,请在请求选项中设置 responseType 参数:

    const file = await service.files.get({
      fileId,
      alt: 'media',
    }, { responseType: 'arraybuffer' });
    
    // Convert the ArrayBuffer to a Node.js Buffer object.
    const buffer = Buffer.from(file.data);
    
  • Python:用于下载 blob 文件的 Python 代码示例已将下载块写入内存中的 io.BytesIO() 对象。如需访问原始字节,请调用 file.getvalue()

  • Java:用于下载 blob 文件的 Java 代码示例使用 java.io.ByteArrayOutputStream 在内存中捕获下载的字节。使用 outputStream.toByteArray() 访问原始字节数组。

  • .NET:用于下载 blob 文件的 C# 代码示例使用 System.IO.MemoryStream。使用 stream.ToArray() 访问底层字节数组。

  • Apps 脚本用于下载 blob 文件的 Apps 脚本代码示例使用 response.getBlob() 方法返回 Blob 对象。使用 getBytes() 方法将其转换为字节数组。

部分下载

部分下载是指仅下载文件的指定部分。您可以使用带有 Range 标头的 字节 范围 来指定要下载的文件部分。例如:

Range: bytes=500-999

下载 blob 文件内容的早期版本

如需下载 blob 文件内容的早期版本,请使用 revisions.get 方法以及要下载的 文件的 ID、修订版本的 ID 和 alt 系统 参数alt=media 参数会告知服务器,系统正在请求下载内容,以作为替代响应格式。与 files.get 类似,revisions.get 方法也接受 acknowledgeAbuse 查询参数和 Range 标头。

您只能下载标记为“永久保留”的 blob 文件内容修订版本。如果您想下载修订版本,请先将其设置为“永久保留”。 如需了解详情,请参阅指定要保存的修订版本,以避免自动删除

如需详细了解如何下载修订版本,请参阅管理长时间运行的 操作

curl

curl -L "https://www.googleapis.com/drive/v3/files/FILE_ID/revisions/REVISION_ID?alt=media" \
  --header "Authorization: Bearer ACCESS_TOKEN" \
  --output "FILE_NAME"

替换以下内容:

  • FILE_ID:要下载的文件的 ID。
  • REVISION_ID:要下载的修订版本的 ID。
  • ACCESS_TOKEN:授予 API 访问权限的访问令牌。
  • FILE_NAME:输出文件的名称。

在浏览器中下载 blob 文件内容

如需在 浏览器中下载存储在云端硬盘上的 blob 文件内容,而不是通过 API 下载,请使用 webContentLink 资源的 files 字段。如果用户具有文件的下载权限,系统会返回用于下载文件及其内容的链接。您可以将用户重定向到该网址,也可以将该网址作为可点击的链接提供给用户。

curl

curl "https://www.googleapis.com/drive/v3/files/FILE_ID?fields=webContentLink" \
  --header "Authorization: Bearer ACCESS_TOKEN" \
  --header "Accept: application/json"

替换以下内容:

  • FILE_ID:用于获取下载链接 的文件的 ID。
  • ACCESS_TOKEN:授予 API 访问权限的访问令牌。

使用长时间运行的操作下载 blob 文件内容

如需使用长时间运行的操作 (LRO) 下载 blob 文件内容,请使用 files.download方法以及要下载的文件的 ID。您可以选择设置修订版本的 ID。

这是下载 Google Vids 文件的唯一方法。如果您尝试导出 Google Vids 文件,则会收到 fileNotExportable 错误。 如需了解详情,请参阅管理长时间运行 的操作

curl

以下 curl 命令会启动 LRO 并返回 JSON 响应。如需下载文件或轮询此 LRO,您必须使用返回的 ID 发出另一个请求,以获取内容网址。然后,您可以向该网址发出最终 curl 请求,以下载文件。如需了解详情,请参阅 管理长时间运行的 操作

curl --request POST "https://www.googleapis.com/drive/v3/files/FILE_ID/download?mimeType=video/mp4" \
  --header "Authorization: Bearer ACCESS_TOKEN" \
  --header "Content-Length: 0" \
  --header "Accept: application/json"

替换以下内容:

  • FILE_ID:要下载的文件的 ID。
  • ACCESS_TOKEN:授予 API 访问权限的访问令牌。

导出 Google Workspace 文档内容

如需导出 Google Workspace 文档字节内容,请使用 files.export 方法以及要导出的文件的 ID 和 正确的 MIME 类型。导出的内容不得超过 10 MB。

以下代码示例展示了如何使用 files.export 方法以 PDF 格式导出 Google Workspace 文档:

Apps 脚本

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

curl

curl -L "https://www.googleapis.com/drive/v3/files/FILE_ID/export?mimeType=application/pdf" \
  --header "Authorization: Bearer ACCESS_TOKEN" \
  --output "FILE_NAME.pdf"

替换以下内容:

  • FILE_ID:要下载的文件的 ID。
  • ACCESS_TOKEN:授予 API 访问权限的访问令牌。
  • FILE_NAME:输出文件的名称。

客户端库代码示例使用受限的 drive 范围,该范围允许用户查看和管理您的所有云端硬盘文件。如需详细了解云端硬盘范围,请参阅 选择 Google Drive API 范围

代码示例还会将导出 MIME 类型声明为 application/pdf。如需查看每个 Google Workspace 文档支持的所有导出 MIME 类型的完整列表,请参阅 Google Workspace 文档的导出 MIME 类型

在浏览器中导出 Google Workspace 文档内容

如需在浏览器中导出 Google Workspace 文档内容,请使用 exportLinks 字段的 files 资源。根据文档类型,系统会为每个可用的 MIME 类型返回用于下载文件及其内容的链接。您可以将用户重定向到网址,也可以将该网址作为可点击的链接提供给用户。

curl

curl "https://www.googleapis.com/drive/v3/files/FILE_ID?fields=id,name,exportLinks" \
  --header "Authorization: Bearer ACCESS_TOKEN" \
  --header "Accept: application/json"

替换以下内容:

  • FILE_ID:用于获取下载链接 的文件的 ID。
  • ACCESS_TOKEN:授予 API 访问权限的访问令牌。

在浏览器中导出 Google Workspace 文档内容的早期版本

如需在 浏览器中导出 Google Workspace 文档内容的早期版本,请使用 revisions.get 方法以及 要下载的文件的 ID 和修订版本的 ID,以生成导出 链接,您可以从中执行下载。如果用户具有文件的下载权限,系统会返回用于下载文件及其内容的链接。您可以将用户重定向到该网址,也可以将该网址作为可点击的链接提供给用户。

curl

curl "https://www.googleapis.com/drive/v3/files/FILE_ID/revisions/REVISION_ID?fields=id,name,exportLinks" \
  --header "Authorization: Bearer ACCESS_TOKEN" \
  --header "Accept: application/json"

替换以下内容:

  • FILE_ID:要下载的文件的 ID。
  • REVISION_ID:要下载的修订版本的 ID。
  • ACCESS_TOKEN:授予 API 访问权限的访问令牌。

使用长时间运行的操作导出 Google Workspace 文档内容

如需使用长时间运行的操作 (LRO) 导出 Google Workspace 文档内容,请使用 files.download 方法以及 要下载的文件的 ID 和修订版本的 ID。如需了解详情, 请参阅管理长时间运行的操作

curl

以下 curl 命令会启动 LRO 并返回 JSON 响应。如需下载文件或轮询此 LRO,您必须使用返回的 ID 发出另一个请求,以获取内容网址。然后,您可以向该网址发出最终 curl 请求,以下载文件。如需了解详情,请参阅 管理长时间运行的 操作

curl --request POST "https://www.googleapis.com/drive/v3/files/FILE_ID/download?mimeType=MIME_TYPE&revisionId=REVISION_ID" \
  --header "Authorization: Bearer ACCESS_TOKEN" \
  --header "Content-Length: 0" \
  --header "Accept: application/json"

替换以下内容:

  • FILE_ID:要下载的文件的 ID。
  • MIME_TYPE:要导出的 MIME 类型。
  • REVISION_ID:要下载的修订版本的 ID。
  • ACCESS_TOKEN:授予 API 访问权限的访问令牌。