הורדה וייצוא של קבצים

ממשק Google Drive API תומך במספר סוגים של פעולות הורדה וייצוא, כפי שמפורט בטבלה הבאה:

הורדות
תוכן של קובץ Blob באמצעות השיטה files.get עם הפרמטר alt=media של כתובת האתר.
תוכן של קובץ מקבלים בגרסה מוקדמת יותר באמצעות השיטה revisions.get עם הפרמטר alt=media של כתובת האתר.
תוכן של קובץ דם בדפדפן באמצעות השדה webContentLink.
ייצוא
תוכן ממסמך ב-Google Workspace בפורמט שהאפליקציה יכולה לטפל בו, באמצעות files.export.
תוכן מסמכים ב-Google Workspace בדפדפן באמצעות השדה exportLinks.
תוכן של מסמכים ב-Google Workspace מגרסה קודמת בדפדפן באמצעות השדה exportLinks.

בהמשך המדריך תמצאו הוראות מפורטות לביצוע פעולות הורדה וייצוא מהסוגים האלה.

הורדת תוכן של קובץ blob

כדי להוריד קובץ blob ששמור ב-Drive, צריך להשתמש בשיטה files.get עם מזהה הקובץ להורדה ואת הפרמטר alt=media של כתובת ה-URL. הפרמטר alt=media של כתובת ה-URL מציין לשרת שמבקשת להוריד תוכן כפורמט חלופי של תגובה.

הפרמטר של כתובת האתר alt=media הוא פרמטר מערכת שזמין בכל ממשקי ה-API ל-REST של Google. אם אתם משתמשים בספריית לקוח עבור ה-API של Drive, לא תצטרכו להגדיר את הפרמטר הזה באופן מפורש.

דוגמת הקוד הבאה ממחישה איך משתמשים בשיטה 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
from __future__ import print_function

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', שמאפשר למשתמשים לראות ולנהל את כל הקבצים שלכם ב-Drive. למידע נוסף על היקפי הרשאות של Drive, ראו מידע על הרשאות ואימות ספציפיות ל-API.

משתמשים עם הרשאות עריכה יכולים להגביל את ההורדה של משתמשים עם הרשאת קריאה בלבד, על ידי הגדרת השדה copyRequiresWriterPermission לערך false.

קבצים שמזוהים כפוגעניים (למשל תוכנה מזיקה) ניתנים להורדה רק על ידי הבעלים של הקובץ. בנוסף, צריך לכלול את פרמטר השאילתה acknowledgeAbuse=true get כדי לציין שהמשתמש הכיר בכך שיש סיכון להורדת תוכנה שעלולה להיות לא רצויה או קבצים זדוניים אחרים. האפליקציה צריכה להציג אזהרה למשתמש באופן אינטראקטיבי לפני השימוש בפרמטר השאילתה הזה.

הורדה חלקית

הורדה חלקית כרוכה בהורדה רק של חלק מסוים מהקובץ. אפשר לציין את החלק בקובץ שרוצים להוריד באמצעות טווח בייטים עם הכותרת Range. לדוגמה:

Range: bytes=500-999

הורדת תוכן של קובץ blob בגרסה קודמת

כדי להוריד את התוכן של קובצי blob בגרסה קודמת, צריך להשתמש בשיטה revisions.get עם מזהה הקובץ להורדה, מזהה הגרסה הקודמת והפרמטר של כתובת ה-URL alt=media. הפרמטר alt=media של כתובת ה-URL מציין לשרת שמתבצעת בקשה להורדת תוכן כפורמט חלופי של תגובה. בדומה לשיטה files.get, השיטה revisions.get מקבלת גם את פרמטר השאילתה האופציונלי acknowledgeAbuse ואת הכותרת Range. למידע נוסף על הורדת גרסאות קודמות, קראו את המאמר הורדה ופרסום של גרסאות קודמות.

הורדת תוכן של קובצי blob בדפדפן

כדי להוריד את התוכן של קובצי blob שמאוחסנים ב-Drive בדפדפן, במקום דרך ה-API, צריך להשתמש בשדה webContentLink במשאב Files. אם למשתמש יש גישת הורדה לקובץ, יוחזר קישור להורדת הקובץ והתוכן שלו. ניתן להפנות את המשתמש לכתובת URL זו או להציע אותה כקישור שניתן ללחוץ עליו.

ייצוא של תוכן מסמכים ב-Google Workspace

כדי לייצא תוכן של בייטים של מסמכים ב-Google Workspace, צריך להשתמש בשיטה files.export עם מזהה הקובץ לייצוא וסוג ה-MIME הנכון. התוכן המיוצא מוגבל ל-10MB.

דוגמת הקוד הבאה מראה איך להשתמש בשיטה 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
from __future__ import print_function

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 המוגבל, שמאפשר למשתמשים לראות ולנהל את כל הקבצים שלכם ב-Drive. מידע נוסף על היקפי ההרשאות של Drive זמין במאמר מידע על הרשאות ואימות ספציפיות ל-API.

בדוגמת הקוד גם מצהירה שסוג ה-MIME לייצוא הוא application/pdf. לרשימה המלאה של כל סוגי ה-MIME בייצוא שנתמכים לכל מסמך ב-Google Workspace, תוכלו לקרוא את המאמר ייצוא סוגי MIME למסמכי Google Workspace.

ייצוא של תוכן מסמכים מ-Google Workspace בדפדפן

כדי לייצא תוכן מסמכים של Google Workspace מתוך דפדפן, יש להשתמש בשדה exportLinks של המשאב Files. בהתאם לסוג המסמך, לכל סוג MIME זמין מוחזר קישור להורדת הקובץ והתוכן שלו. תוכלו להפנות את המשתמש לכתובת URL או להציע אותה כקישור שניתן ללחוץ עליו.

ייצוא של תוכן מסמכים של Google Workspace מגרסה קודמת בדפדפן

כדי לייצא תוכן של מסמכים ב-Google Workspace מגרסה קודמת בדפדפן, צריך להשתמש ב-method revisions.get עם מזהה הקובץ להורדה ומזהה הגרסה הקודמת. אם למשתמש יש גישת הורדה לקובץ, יוחזר קישור להורדת הקובץ והתוכן שלו. ניתן להפנות את המשתמש לכתובת URL זו או להציע אותה כקישור שניתן ללחוץ עליו.