ดาวน์โหลดและส่งออกไฟล์

API ของ Google ไดรฟ์รองรับการดาวน์โหลดและส่งออกหลายประเภท เช่น แสดงในตารางต่อไปนี้

การดาวน์โหลด
เนื้อหาไฟล์ Blob โดยใช้เมธอด files.get กับพารามิเตอร์ของ URL alt=media
เนื้อหาไฟล์ Blob ในเวอร์ชันก่อนหน้าโดยใช้เมธอด revisions.get กับพารามิเตอร์ URL alt=media
เนื้อหาไฟล์ Blob ในเบราว์เซอร์ที่ใช้ฟิลด์ webContentLink
การส่งออก
เนื้อหาในเอกสาร Google Workspace ในรูปแบบที่แอปของคุณสามารถจัดการได้ โดยใช้ files.export
เนื้อหาเอกสาร Google Workspace ในเบราว์เซอร์ที่ใช้ช่อง exportLinks
เนื้อหาเอกสารใน Google Workspace เวอร์ชันก่อนหน้าในเบราว์เซอร์ที่ใช้ช่อง exportLinks

ก่อนดาวน์โหลดหรือส่งออกเนื้อหาไฟล์ โปรดยืนยันว่าผู้ใช้จะดาวน์โหลดหรือส่งออกเนื้อหาไฟล์ได้ โดยใช้ฟิลด์ capabilities.canDownload ใน แหล่งข้อมูล files

ส่วนที่เหลือของคู่มือนี้จะให้คำแนะนำโดยละเอียดสำหรับการดำเนินการประเภทเหล่านี้ ของการดาวน์โหลดและส่งออก

ดาวน์โหลดเนื้อหาไฟล์ BLOB

หากต้องการดาวน์โหลดไฟล์ BLOB ที่จัดเก็บไว้ในไดรฟ์ ให้ใช้เมธอด files.get ที่มีรหัสไฟล์ที่จะดาวน์โหลด และพารามิเตอร์ URL alt=media พารามิเตอร์ของ URL alt=media จะบอก เซิร์ฟเวอร์ที่มีการขอให้ดาวน์โหลดเนื้อหาเป็นการตอบสนองทางเลือก

พารามิเตอร์ URL 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;
        }
    }
}

ตัวอย่างโค้ดนี้ใช้วิธีการไลบรารีที่เพิ่มพารามิเตอร์ของ URL alt=media ลงในคำขอ HTTP ที่สำคัญ

การดาวน์โหลดไฟล์ที่เริ่มต้นจากแอปจะต้องได้รับอนุญาตด้วยขอบเขตที่ให้สิทธิ์ สิทธิ์การอ่านเนื้อหาไฟล์ เช่น แอปที่ใช้ ขอบเขต drive.readonly.metadata ไม่ได้รับอนุญาตให้ดาวน์โหลดเนื้อหาของไฟล์ ตัวอย่างโค้ดนี้ใช้ขอบเขตไฟล์ "ไดรฟ์" แบบจำกัดซึ่งอนุญาตให้ผู้ใช้ ดูและจัดการไฟล์ในไดรฟ์ทั้งหมดของคุณ หากต้องการทราบข้อมูลเพิ่มเติมเกี่ยวกับ ขอบเขตของไดรฟ์ โปรดดูที่เลือก Google Drive API ขอบเขต

ผู้ใช้ที่มีสิทธิ์แก้ไขสามารถจำกัดการดาวน์โหลดโดยผู้ใช้แบบอ่านอย่างเดียวได้ผ่าน กำลังตั้งค่า copyRequiresWriterPermission เป็น false

ไฟล์ระบุว่า ละเมิด (เช่น ซอฟต์แวร์ที่เป็นอันตราย) จะมีเพียงเจ้าของไฟล์เท่านั้นที่สามารถดาวน์โหลดได้ นอกจากนี้ คุณต้องใส่ get พารามิเตอร์การค้นหา acknowledgeAbuse=true ด้วย เพื่อระบุว่าผู้ใช้รับทราบถึงความเสี่ยงในการดาวน์โหลด ซอฟต์แวร์ไม่พึงประสงค์หรือไฟล์ที่เป็นการละเมิดอื่นๆ แอปพลิเคชันของคุณควรมีการโต้ตอบ เตือนผู้ใช้ก่อนใช้พารามิเตอร์การค้นหานี้

ดาวน์โหลดบางส่วน

การดาวน์โหลดบางส่วนเกี่ยวข้องกับการดาวน์โหลดเฉพาะบางส่วนของไฟล์ คุณ สามารถระบุส่วนของไฟล์ที่คุณต้องการดาวน์โหลดโดยใช้ไบต์ ช่วง ที่มีส่วนหัว Range เช่น

Range: bytes=500-999

ดาวน์โหลดเนื้อหาไฟล์ BLOB ในเวอร์ชันก่อนหน้า

หากต้องการดาวน์โหลดเนื้อหาของไฟล์ BLOB ในเวอร์ชันก่อนหน้า ให้ใช้ เมธอด revisions.get ที่มีรหัสของ ไฟล์ที่จะดาวน์โหลด รหัสของการแก้ไข และพารามิเตอร์ URL alt=media พารามิเตอร์ของ URL alt=media จะบอกเซิร์ฟเวอร์ว่าการดาวน์โหลดเนื้อหา มีการขอให้เป็นรูปแบบคำตอบทางเลือก เช่นเดียวกับ files.get วิธี revisions.get ยังยอมรับพารามิเตอร์การค้นหาที่ไม่บังคับด้วย acknowledgeAbuse และส่วนหัว Range สำหรับข้อมูลเพิ่มเติมเกี่ยวกับการดาวน์โหลด การแก้ไข โปรดดูดาวน์โหลดและเผยแพร่ไฟล์ การแก้ไขดังกล่าว

ดาวน์โหลดเนื้อหาไฟล์ Blob ในเบราว์เซอร์

หากต้องการดาวน์โหลดเนื้อหาของไฟล์ Blob ที่จัดเก็บในไดรฟ์ภายใน แทนการดำเนินการผ่าน API ให้ใช้ ฟิลด์ webContentLink ของฟิลด์ แหล่งข้อมูล files หากผู้ใช้มีการดาวน์โหลด การเข้าถึงไฟล์ ลิงก์สำหรับดาวน์โหลดไฟล์ และเนื้อหาในไฟล์ ส่งคืนแล้ว คุณสามารถเปลี่ยนเส้นทางผู้ใช้ไปยัง URL นี้ หรือเสนอให้เป็น URL ที่คลิกได้ ลิงก์

ส่งออกเนื้อหาเอกสารใน Google Workspace

หากต้องการส่งออกเนื้อหาไบต์ในเอกสารของ Google Workspace ให้ใช้เมธอด files.export ที่มีรหัสไฟล์ที่จะส่งออก และประเภท MIME ที่ถูกต้อง ส่งออกแล้ว เนื้อหาต้องมีขนาดไม่เกิน 10 MB

ตัวอย่างโค้ดต่อไปนี้แสดงวิธีใช้เมธอด files.export เพื่อส่งออก เอกสารของ Google Workspace ในรูปแบบ PDF โดยใช้ไคลเอ็นต์ Drive API ไลบรารี:

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 ด้วย สำหรับ รายการประเภท MIME ส่งออกทั้งหมดที่รองรับสำหรับ Google Workspace แต่ละรายการ โปรดดูเอกสารที่หัวข้อส่งออกประเภท MIME สำหรับ Google Workspace เอกสาร

ส่งออกเนื้อหาเอกสาร Google Workspace ในเบราว์เซอร์

หากต้องการส่งออกเนื้อหาเอกสารใน Google Workspace ภายในเบราว์เซอร์ ให้ใช้เมธอด ฟิลด์ exportLinks ของฟิลด์ แหล่งข้อมูล files ทั้งนี้ขึ้นอยู่กับเอกสาร ประเภท ลิงก์สำหรับดาวน์โหลดไฟล์ และเนื้อหาในไฟล์จะแสดงผลสำหรับ MIME ทั้งหมด ประเภทที่มีให้เลือก คุณสามารถเปลี่ยนเส้นทางผู้ใช้ไปยัง URL หรือเสนอให้เป็น URL ลิงก์ที่คลิกได้

ส่งออกเนื้อหาของเอกสาร Google Workspace เวอร์ชันก่อนหน้าในเบราว์เซอร์

หากต้องการส่งออกเนื้อหาของเอกสาร Google Workspace เป็นเวอร์ชันก่อนหน้าภายใน เบราว์เซอร์ ให้ใช้เมธอด revisions.get พร้อมรหัสของไฟล์ที่จะดาวน์โหลดและรหัสของการแก้ไข หากผู้ใช้มี สิทธิ์ดาวน์โหลดไฟล์ ลิงก์สำหรับดาวน์โหลดไฟล์ และเนื้อหาในไฟล์ ส่งคืนแล้ว คุณสามารถเปลี่ยนเส้นทางผู้ใช้ไปยัง URL นี้ หรือเสนอให้เป็น URL ที่คลิกได้ ลิงก์