تنزيل الملفات وتصديرها

تتيح واجهة برمجة التطبيقات Google Drive API عدة أنواع من إجراءات التنزيل والتصدير، كما هو موضّح في الجدول التالي:

عمليات التنزيل
محتوى ملف Blob باستخدام الطريقة files.get مع معلَمة عنوان URL للسمة alt=media.
محتوى ملف Blob في إصدار سابق باستخدام الطريقة revisions.get مع معلَمة عنوان URL للسمة alt=media.
محتوى ملف Blob في متصفّح باستخدام الحقل webContentLink.
عمليات التصدير
محتوى مستند Google Workspace بتنسيق يمكن لتطبيقك التعامل معه باستخدام files.export.
محتوى مستند Google Workspace في متصفّح باستخدام الحقل exportLinks
محتوى مستند Google Workspace في إصدار سابق في متصفّح باستخدام الحقل exportLinks

يوفر الجزء المتبقي من هذا الدليل إرشادات مفصلة لتنفيذ هذه الأنواع من إجراءات التنزيل والتصدير.

تنزيل محتوى ملف blob

لتنزيل ملف ثنائي كبير مخزَّن على Drive، استخدِم الطريقة files.get مع رقم تعريف الملف المطلوب تنزيله ومَعلمة عنوان URL للسمة alt=media. توضِّح معلَمة عنوان URL alt=media للخادم أنّه يتم طلب تنزيل المحتوى كتنسيق استجابة بديل.

معلَمة عنوان URL alt=media هي مَعلمة نظام متوفّرة في جميع واجهات برمجة تطبيقات Google REST. إذا كنت تستخدم مكتبة برامج لواجهة برمجة تطبيقات 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;
  }
}

‫2,999

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 غير مسموح له بتنزيل محتوى الملف. يستخدم نموذج الرمز هذا نطاق ملف "Drive" المشروط الذي يسمح للمستخدمين بعرض جميع ملفات Drive وإدارتها. لمعرفة المزيد من المعلومات عن نطاقات Drive، يمكنك الرجوع إلى معلومات المصادقة والترخيص المتعلقة بواجهة برمجة التطبيقات.

يمكن للمستخدمين الذين لديهم أذونات للتعديل حظر التنزيل من قِبل مستخدمين لديهم الإذن بالقراءة فقط، وذلك من خلال ضبط الحقل 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 التي تم تخزينها على Drive في متصفح، بدلاً من استخدام واجهة برمجة التطبيقات، استخدم الحقل webContentLink لمورد Files. إذا كان لدى المستخدم حق الوصول للتنزيل إلى الملف، يتم عرض رابط لتنزيل الملف ومحتواه. يمكنك إما إعادة توجيه المستخدم إلى عنوان URL هذا أو عرضه كرابط قابل للنقر.

تصدير محتوى مستند Google Workspace

لتصدير محتوى بايت في مستند Google Workspace، استخدِم طريقة files.export مع معرّف الملف المطلوب تصديره ونوع MIME الصحيح. يقتصر حجم المحتوى المصدَّر على 10 ميغابايت.

يوضّح نموذج الرمز التالي كيفية استخدام طريقة 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;
  }
}

‫2,999

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، يمكنك الرجوع إلى معلومات التفويض والمصادقة الخاصة بواجهة برمجة التطبيقات.

يعرِّف نموذج الرمز أيضًا نوع MIME للتصدير على أنّه application/pdf. للحصول على قائمة كاملة بجميع أنواع MIME للتصدير المتوافقة مع كل مستند من مستندات Google Workspace، يمكنك الرجوع إلى تصدير أنواع MIME لمستندات Google Workspace.

تصدير محتوى مستند Google Workspace في متصفح

لتصدير محتوى مستند Google Workspace في متصفّح، استخدِم الحقل exportLinks في المورد Files. بناءً على نوع المستند، يتم عرض رابط لتنزيل الملف ومحتواه لكل نوع MIME متاح. يمكنك إما إعادة توجيه المستخدم إلى عنوان URL أو تقديمه كرابط قابل للنقر.

تصدير محتوى مستند Google Workspace إلى إصدار سابق في متصفّح

لتصدير محتوى مستند Google Workspace في إصدار سابق ضمن متصفّح، استخدِم طريقة revisions.get مع رقم تعريف الملف لتنزيله ورقم تعريف النسخة السابقة. إذا كان لدى المستخدم حق الوصول للتنزيل إلى الملف، يتم عرض رابط لتنزيل الملف ومحتواه. يمكنك إما إعادة توجيه المستخدم إلى عنوان URL هذا أو عرضه كرابط قابل للنقر.