下载和导出文件

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 网址参数是一种系统参数,适用于所有 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。

以下代码示例展示了如何使用 Drive API 客户端库通过 files.export 方法以 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。如需了解详情,请参阅管理长时间运行的操作

限制文件的共享方式