下载和导出文件

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 范围

拥有修改权限的用户可以通过将 copyRequiresWriterPermission 字段设置为 false 来限制只读用户下载内容。

被标识为滥用性的文件(例如有害软件)只有文件所有者才能下载。此外,必须添加 get 查询参数 acknowledgeAbuse=true,以表明用户已确认下载潜在不需要的软件或其他滥用文件的风险。您的应用应在使用此查询参数之前以互动方式向用户发出警告。

部分下载

执行部分下载时,系统只会下载文件的指定部分。您可以将字节范围Range 标头搭配使用,以指定要下载的文件部分。例如:

Range: bytes=500-999

下载较低版本的 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 文件内容

如需在浏览器中(而非通过 API)下载存储在云端硬盘上的 blob 文件的内容,请使用 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。如需了解详情,请参阅管理长时间运行的操作