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

Google Drive API รองรับการดำเนินการดาวน์โหลดและส่งออกหลายประเภทตามที่ระบุไว้ในตารางต่อไปนี้

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

ใน Drive API ไฟล์ Blob หมายถึงไฟล์ไบนารีแบบดิบที่จัดเก็บไว้ใน Google ไดรฟ์ (เช่น รูปภาพ วิดีโอ และ PDF) ซึ่งแตกต่างจากเอกสาร Google Workspace และไม่ได้หมายถึงออบเจ็กต์ Blob ของ JavaScript ดูคำอธิบายโดยละเอียดเกี่ยวกับประเภทไฟล์ที่กล่าวถึงที่นี่ ซึ่งรวมถึงไฟล์ Blob และไฟล์ Google Workspace ได้ที่ประเภท ไฟล์

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

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

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

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

พารามิเตอร์ระบบ alt มีให้บริการใน Google REST API ทั้งหมด หากคุณใช้ไลบรารีของไคลเอ็นต์ Drive API คุณไม่จำเป็นต้องตั้งค่าพารามิเตอร์นี้อย่างชัดเจน เนื่องจากเมธอดไลบรารีของไคลเอ็นต์จะเพิ่มพารามิเตอร์ alt=media ลงในคำขอ HTTP ที่เกี่ยวข้อง

ตัวอย่างโค้ดต่อไปนี้แสดงวิธีใช้วิธี files.get เพื่อดาวน์โหลดไฟล์

Apps Script

/**
 * 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: รหัสของไฟล์ที่จะดาวน์โหลด
  • 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: ตัวอย่างโค้ด Python สำหรับดาวน์โหลดไฟล์ Blob จะเขียน Chunk ที่ดาวน์โหลดลงในออบเจ็กต์ io.BytesIO() ในหน่วยความจำอยู่แล้ว หากต้องการเข้าถึงไบต์แบบดิบ ให้เรียก file.getvalue()

  • Java: ตัวอย่างโค้ด Java สำหรับดาวน์โหลดไฟล์ Blob ใช้ java.io.ByteArrayOutputStream เพื่อบันทึกไบต์ที่ดาวน์โหลดในหน่วยความจำ ใช้ outputStream.toByteArray() เพื่อเข้าถึงอาร์เรย์ไบต์แบบดิบ

  • .NET: ตัวอย่างโค้ด C# สำหรับดาวน์โหลด ไฟล์ Blob ใช้ System.IO.MemoryStream ใช้ stream.ToArray() เพื่อเข้าถึงอาร์เรย์ไบต์ที่เกี่ยวข้อง

  • Apps Script: ตัวอย่างโค้ด Apps Script สำหรับดาวน์โหลดไฟล์ Blobใช้วิธี response.getBlob() เพื่อแสดงผลออบเจ็กต์ Blob แปลงออบเจ็กต์นี้เป็นอาร์เรย์ไบต์โดยใช้วิธี getBytes()

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

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

Range: bytes=500-999

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

หากต้องการดาวน์โหลดเนื้อหาไฟล์ Blob ในเวอร์ชันก่อนหน้า ให้ใช้วิธี revisions.get กับรหัสของ ไฟล์ที่จะดาวน์โหลด รหัสของการแก้ไข และ 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: รหัสของไฟล์ที่จะดาวน์โหลด
  • REVISION_ID: รหัสของการแก้ไขที่จะดาวน์โหลด
  • ACCESS_TOKEN: โทเค็นเพื่อการเข้าถึงที่ให้สิทธิ์เข้าถึง API
  • FILE_NAME: ชื่อของไฟล์เอาต์พุต

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

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

curl

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

แทนที่ค่าต่อไปนี้

  • FILE_ID: รหัสของไฟล์ที่จะรับลิงก์ดาวน์โหลด
  • ACCESS_TOKEN: โทเค็นเพื่อการเข้าถึงที่ให้สิทธิ์เข้าถึง API

ดาวน์โหลดเนื้อหาไฟล์ Blob โดยใช้การดำเนินการที่ใช้เวลานาน

หากต้องการดาวน์โหลดเนื้อหาไฟล์ Blob โดยใช้การดำเนินการที่ใช้เวลานาน (LRO) ให้ใช้ เมธอด files.download กับรหัสของ ไฟล์ที่จะดาวน์โหลด คุณสามารถตั้งค่ารหัสของการแก้ไขได้ (ไม่บังคับ)

ซึ่งเป็นวิธีเดียวในการดาวน์โหลดไฟล์ Google Vids หากพยายามส่งออก ไฟล์ Google Vids คุณจะได้รับข้อผิดพลาด fileNotExportable ดูข้อมูลเพิ่มเติมได้ที่หัวข้อ จัดการการดำเนินการที่ใช้เวลานาน

curl

คำสั่ง curl ต่อไปนี้จะเริ่มต้น LRO และแสดงผลการตอบกลับ JSON หากต้องการดาวน์โหลดไฟล์หรือสำรวจ LRO นี้ คุณต้องส่งคำขออื่นโดยใช้รหัสที่แสดงผลเพื่อรับ URL เนื้อหา จากนั้นคุณก็ส่งคำขอ curl สุดท้ายไปยัง URL นั้นเพื่อดาวน์โหลดไฟล์ได้ ดูข้อมูลเพิ่มเติมได้ที่หัวข้อ จัดการการดำเนินการที่ใช้เวลานาน

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: รหัสของไฟล์ที่จะดาวน์โหลด
  • ACCESS_TOKEN: โทเค็นเพื่อการเข้าถึงที่ให้สิทธิ์เข้าถึง API

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

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

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

Apps Script

/**
 * 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: รหัสของไฟล์ที่จะดาวน์โหลด
  • ACCESS_TOKEN: โทเค็นเพื่อการเข้าถึงที่ให้สิทธิ์เข้าถึง API
  • FILE_NAME: ชื่อของไฟล์เอาต์พุต

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

ตัวอย่างโค้ดยังประกาศประเภท MIME ของการส่งออกเป็น application/pdf ด้วย ดูรายการประเภท MIME ของการส่งออกทั้งหมดที่รองรับสำหรับเอกสาร Google Workspace แต่ละรายการได้ที่หัวข้อ ประเภท MIME ของการส่งออกสำหรับเอกสาร Google Workspace

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

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

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: รหัสของไฟล์ที่จะรับลิงก์ดาวน์โหลด
  • ACCESS_TOKEN: โทเค็นเพื่อการเข้าถึงที่ให้สิทธิ์เข้าถึง API

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

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

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: รหัสของไฟล์ที่จะดาวน์โหลด
  • REVISION_ID: รหัสของการแก้ไขที่จะดาวน์โหลด
  • ACCESS_TOKEN: โทเค็นเพื่อการเข้าถึงที่ให้สิทธิ์เข้าถึง API

ส่งออกเนื้อหาเอกสาร Google Workspace โดยใช้การดำเนินการที่ใช้เวลานาน

หากต้องการส่งออกเนื้อหาเอกสาร Google Workspace โดยใช้การดำเนินการที่ใช้เวลานาน (LRO) ให้ใช้วิธี files.download กับ รหัสของไฟล์ที่จะดาวน์โหลดและรหัสของการแก้ไข ดูข้อมูลเพิ่มเติมได้ที่ หัวข้อจัดการการดำเนินการที่ใช้เวลานาน

curl

คำสั่ง curl ต่อไปนี้จะเริ่มต้น LRO และแสดงผลการตอบกลับ JSON หากต้องการดาวน์โหลดไฟล์หรือสำรวจ LRO นี้ คุณต้องส่งคำขออื่นโดยใช้รหัสที่แสดงผลเพื่อรับ URL เนื้อหา จากนั้นคุณก็ส่งคำขอ curl สุดท้ายไปยัง URL นั้นเพื่อดาวน์โหลดไฟล์ได้ ดูข้อมูลเพิ่มเติมได้ที่หัวข้อ จัดการการดำเนินการที่ใช้เวลานาน

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: รหัสของไฟล์ที่จะดาวน์โหลด
  • MIME_TYPE: ประเภท MIME ที่จะส่งออก
  • REVISION_ID: รหัสของการแก้ไขที่จะดาวน์โหลด
  • ACCESS_TOKEN: โทเค็นเพื่อการเข้าถึงที่ให้สิทธิ์เข้าถึง API