Tải tệp xuống và xuất

API Google Drive hỗ trợ một số loại thao tác tải xuống và xuất, chẳng hạn như được liệt kê trong bảng sau:

Tải video xuống
Nội dung trong tệp mở rộng bằng phương thức files.get với tham số URL alt=media.
Làm mờ nội dung tệp ở phiên bản cũ bằng cách sử dụng phương thức revisions.get với tham số URL alt=media.
Blob nội dung tệp trong trình duyệt bằng cách sử dụng trường webContentLink.
Xuất dữ liệu
Nội dung trong tài liệu trên Google Workspaceđịnh dạng mà ứng dụng của bạn có thể xử lý bằng files.export.
Nội dung tài liệu trên Google Workspace trong một trình duyệt bằng cách sử dụng trường exportLinks.
Nội dung tài liệu trên Google Workspace ở phiên bản cũ trong trình duyệt bằng cách sử dụng trường exportLinks.

Trước khi bạn tải xuống hoặc xuất nội dung tệp, hãy xác minh rằng người dùng có thể tải bằng cách sử dụng trường capabilities.canDownload trên Tài nguyên files.

Phần còn lại của hướng dẫn này cung cấp hướng dẫn chi tiết về cách thực hiện các loại nội dung này hành động tải xuống và xuất.

Tải nội dung tệp blob xuống

Để tải tệp blob lưu trữ trên Drive xuống, hãy sử dụng phương thức files.get kèm theo mã nhận dạng của tệp cần tải xuống và tham số URL alt=media. Tham số URL alt=media cho biết máy chủ yêu cầu tải nội dung xuống làm phản hồi thay thế .

Tham số URL alt=media là một hệ thống tham số có sẵn trên tất cả các API REST của Google. Nếu bạn sử dụng thư viện ứng dụng cho API Drive, bạn không cần phải đặt tham số này một cách rõ ràng.

Mã mẫu sau đây cho biết cách sử dụng phương thức files.get để tải một tệp bằng thư viện ứng dụng API Drive.

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

Mã mẫu này sử dụng phương thức thư viện có thêm tham số URL alt=media đến yêu cầu HTTP cơ bản.

Các tệp tải xuống bắt đầu từ ứng dụng của bạn phải được cấp phép với phạm vi cho phép quyền đọc nội dung tệp. Ví dụ: một ứng dụng sử dụng Phạm vi drive.readonly.metadata không được phép tải nội dung tệp xuống. Mã mẫu này sử dụng phạm vi tệp "drive" bị hạn chế cho phép người dùng xem và quản lý tất cả các tệp của bạn trên Drive. Để tìm hiểu thêm về Phạm vi Drive, tham khảo bài viết Chọn API Google Drive các phạm vi.

Người dùng có quyền chỉnh sửa có thể hạn chế người dùng chỉ có quyền đọc thông qua việc tải xuống thiết lập copyRequiresWriterPermission sang false.

Tệp được xác định là lạm dụng (chẳng hạn như phần mềm độc hại) chỉ chủ sở hữu tệp mới có thể tải xuống. Ngoài ra, bạn phải thêm tham số truy vấn get acknowledgeAbuse=true để cho biết rằng người dùng đã xác nhận rủi ro về khả năng tải xuống phần mềm không mong muốn hoặc các tệp lạm dụng khác. Ứng dụng của bạn nên có tính tương tác hãy cảnh báo người dùng trước khi sử dụng tham số truy vấn này.

Tải xuống một phần

Tải xuống một phần chỉ bao gồm tải xuống một phần được chỉ định của tệp. Bạn có thể chỉ định phần tệp bạn muốn tải xuống bằng cách sử dụng byte phạm vi với tiêu đề Range. Ví dụ:

Range: bytes=500-999

Tải nội dung tệp blob ở phiên bản cũ xuống

Để tải xuống nội dung của các tệp blob ở phiên bản cũ hơn, hãy sử dụng Phương thức revisions.get có mã nhận dạng là tệp cần tải xuống, mã bản sửa đổi và tham số URL alt=media. Tham số URL alt=media cho máy chủ biết rằng một lượt tải nội dung xuống được yêu cầu làm định dạng phản hồi thay thế. Tương tự như files.get, Phương thức revisions.get cũng chấp nhận tham số truy vấn không bắt buộc acknowledgeAbuse và tiêu đề Range. Để biết thêm thông tin về việc tải xuống bản sửa đổi, hãy xem Tải tệp xuống và xuất bản bản sửa đổi.

Tải nội dung tệp blob xuống trong trình duyệt

Để tải xuống nội dung của các tệp blob được lưu trữ trên Drive trong trình duyệt, thay vì thông qua API, hãy sử dụng Trường webContentLink của files. Nếu người dùng đã tải xuống truy cập vào tệp, liên kết để tải tệp xuống và nội dung của tệp là bị trả lại. Bạn có thể chuyển hướng người dùng đến URL này hoặc cung cấp dưới dạng một URL có thể nhấp vào .

Xuất nội dung tài liệu trên Google Workspace

Để xuất nội dung byte tài liệu trên Google Workspace, hãy sử dụng phương thức files.export kèm theo mã nhận dạng của tệp cần xuất và đúng loại MIME. Đã xuất nội dung được giới hạn ở 10 MB.

Mã mẫu sau đây cho biết cách sử dụng phương thức files.export để xuất một Tài liệu trên Google Workspace ở định dạng PDF bằng ứng dụng Drive API thư viện:

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

Mã mẫu này sử dụng phạm vi drive bị hạn chế để cho phép người dùng xem và quản lý tất cả các tệp của bạn trên Drive. Để tìm hiểu thêm về Phạm vi Drive, tham khảo bài viết Chọn API Google Drive các phạm vi.

Mã mẫu này cũng khai báo loại MIME xuất là application/pdf. Đối với danh sách đầy đủ tất cả các loại MIME xuất được hỗ trợ cho mỗi Google Workspace tài liệu này, hãy tham khảo bài viết Xuất các loại MIME cho Google Workspace tài liệu.

Xuất nội dung tài liệu trên Google Workspace ra trình duyệt

Để xuất nội dung tài liệu trên Google Workspace trong một trình duyệt, hãy sử dụng Trường exportLinks của Tài nguyên files. Tuỳ thuộc vào giấy tờ loại, một liên kết để tải xuống tệp cùng với nội dung của tệp được trả về cho mỗi MIME loại có sẵn. Bạn có thể chuyển hướng người dùng đến một URL hoặc cung cấp URL đó dưới dạng đường liên kết có thể nhấp vào.

Xuất nội dung tài liệu trên Google Workspace ở phiên bản cũ trên trình duyệt

Để xuất nội dung tài liệu trên Google Workspace ở phiên bản cũ trong một trình duyệt, hãy sử dụng phương thức revisions.get có mã nhận dạng của tệp cần tải xuống và mã bản sửa đổi. Nếu người dùng có quyền tải xuống tệp, liên kết để tải tệp xuống và nội dung của tệp là bị trả lại. Bạn có thể chuyển hướng người dùng đến URL này hoặc cung cấp dưới dạng một URL có thể nhấp vào .