فایل ها را دانلود و صادر کنید

API گوگل درایو از چندین نوع عملیات دانلود و خروجی پشتیبانی می‌کند که در جدول زیر فهرست شده‌اند:

دانلود اکشن‌ها
محتوای فایل Blob با استفاده از متد files.get به همراه پارامتر alt=media URL.
محتوای فایل Blob در نسخه‌های قبلی با استفاده از متد revisions.get به همراه پارامتر alt=media URL.
محتوای فایل Blob در مرورگر با استفاده از فیلد webContentLink .
محتوای فایل Blob با استفاده از متد files.download در طول عملیات طولانی مدت. این تنها راه دانلود فایل‌های Google Vids است.
اقدامات صادراتی
محتوای سند Google Workspace را با فرمتی که برنامه شما می‌تواند با استفاده از متد files.export مدیریت کند، ذخیره کنید.
محتوای سند Google Workspace در مرورگر با استفاده از فیلد exportLinks .
محتوای سند Google Workspace در نسخه قبلی در مرورگر با استفاده از فیلد exportLinks .
محتوای سند Google Workspace با استفاده از متد files.download در طول عملیات طولانی مدت.

قبل از دانلود یا اکسپورت کردن محتوای فایل، با استفاده از فیلد capabilities.canDownload در منبع files ، مطمئن شوید که کاربران می‌توانند فایل را دانلود کنند.

برای توضیحات انواع فایل‌های ذکر شده در اینجا، از جمله فایل‌های blob و Google Workspace، به انواع فایل مراجعه کنید.

ادامه‌ی این راهنما، دستورالعمل‌های دقیقی برای انجام این نوع اقدامات دانلود و اکسپورت ارائه می‌دهد.

دانلود محتوای فایل blob

برای دانلود یک فایل blob ذخیره شده در Drive، از متد files.get به همراه شناسه فایل مورد نظر برای دانلود و پارامتر alt=media URL استفاده کنید. پارامتر alt=media URL به سرور می‌گوید که دانلود محتوا به عنوان یک فرمت پاسخ جایگزین درخواست شده است.

پارامتر alt=media URL یک پارامتر سیستمی است که در تمام APIهای REST گوگل موجود است. اگر از یک کتابخانه کلاینت برای Drive API استفاده می‌کنید، نیازی به تنظیم صریح این پارامتر ندارید.

نمونه کد زیر نحوه استفاده از متد files.get برای دانلود یک فایل با استفاده از کتابخانه‌های کلاینت Drive API را نشان می‌دهد.

جاوا

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

پایتون

‎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")

نود جی اس

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

پی اچ پی

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

}

دات نت

‎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 URL را به درخواست HTTP مربوطه اضافه می‌کند.

دانلود فایل‌هایی که از برنامه شما شروع می‌شوند باید با دامنه‌ای مجاز شوند که امکان دسترسی خواندن به محتوای فایل را فراهم کند. برای مثال، برنامه‌ای که از دامنه drive.readonly.metadata استفاده می‌کند، مجاز به دانلود محتوای فایل نیست. این نمونه کد از دامنه فایل محدود شده "drive" استفاده می‌کند که به کاربران امکان مشاهده و مدیریت تمام فایل‌های Drive شما را می‌دهد. برای کسب اطلاعات بیشتر در مورد دامنه‌های Drive، به دامنه‌های Choose Google Drive API مراجعه کنید.

کاربرانی که دارای مجوزهای owner (برای فایل‌های درایو من) یا مجوزهای organizer (برای فایل‌های درایو مشترک) هستند، می‌توانند دانلود را از طریق شیء DownloadRestrictionsMetadata محدود کنند. برای اطلاعات بیشتر، به بخش جلوگیری از دانلود، چاپ یا کپی کردن فایل توسط کاربران مراجعه کنید.

فایل‌هایی که به عنوان فایل‌های مخرب (مانند نرم‌افزارهای مضر) شناسایی می‌شوند، فقط توسط مالک فایل قابل دانلود هستند. علاوه بر این، پارامتر get query یعنی acknowledgeAbuse=true باید گنجانده شود تا نشان دهد که کاربر خطر دانلود نرم‌افزارهای ناخواسته یا سایر فایل‌های مخرب را پذیرفته است. برنامه شما باید قبل از استفاده از این پارامتر، به صورت تعاملی به کاربر هشدار دهد.

دانلود جزئی

دانلود جزئی شامل دانلود فقط بخش مشخصی از یک فایل است. می‌توانید با استفاده از یک محدوده بایت در سربرگ Range ، بخشی از فایل را که می‌خواهید دانلود کنید، مشخص کنید. برای مثال:

Range: bytes=500-999

دانلود محتوای فایل blob در نسخه قبلی

شما فقط می‌توانید نسخه‌های محتوای فایل blob را که با عنوان "Keep Forever" علامت‌گذاری شده‌اند، دانلود کنید. اگر می‌خواهید یک نسخه را دانلود کنید، ابتدا آن را روی "Keep Forever" تنظیم کنید. برای اطلاعات بیشتر، به بخش "مشخص کردن نسخه‌ها برای ذخیره از حذف خودکار" مراجعه کنید.

برای دانلود محتوای فایل‌های blob در نسخه‌های قدیمی‌تر، از متد revisions.get به همراه شناسه فایل مورد نظر برای دانلود، شناسه نسخه و پارامتر alt=media URL استفاده کنید. پارامتر alt=media URL به سرور می‌گوید که دانلود محتوا به عنوان یک فرمت پاسخ جایگزین درخواست شده است. مشابه files.get ، متد revisions.get پارامتر پرس‌وجوی اختیاری acknowledgeAbuse و سربرگ Range را نیز می‌پذیرد. برای اطلاعات بیشتر، به مدیریت عملیات طولانی‌مدت مراجعه کنید.

پروتکل درخواست در اینجا نشان داده شده است.

GET https://www.googleapis.com/drive/v3/files/{FILE_ID}/revisions/{REVISION_ID}?alt=media

دانلود محتوای فایل blob در مرورگر

برای دانلود محتوای فایل‌های blob ذخیره شده در Drive از طریق مرورگر، به جای API، از فیلد webContentLink در منبع files استفاده کنید. اگر کاربر دسترسی دانلود به فایل را داشته باشد، لینکی برای دانلود فایل و محتویات آن بازگردانده می‌شود. می‌توانید کاربر را به این URL هدایت کنید یا آن را به عنوان یک لینک قابل کلیک ارائه دهید.

دانلود محتوای فایل blob در طول عملیات طولانی مدت

برای دانلود محتوای فایل‌های blob در طول عملیات طولانی‌مدت، از متد files.download به همراه شناسه فایل مورد نظر برای دانلود استفاده کنید. می‌توانید به صورت اختیاری شناسه نسخه را تنظیم کنید. این تنها راه دانلود فایل‌های Google Vids است. برای اطلاعات بیشتر، به مدیریت عملیات طولانی‌مدت مراجعه کنید.

محتوای سند Google Workspace را صادر کنید

برای صادر کردن محتوای بایت سند Google Workspace، از متد files.export به همراه شناسه فایل مورد نظر برای صادر کردن و نوع MIME صحیح استفاده کنید. محتوای صادر شده به 10 مگابایت محدود می‌شود.

نمونه کد زیر نحوه استفاده از متد files.export برای خروجی گرفتن از یک سند Google Workspace با فرمت PDF با استفاده از کتابخانه‌های کلاینت Drive API را نشان می‌دهد:

جاوا

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

پایتون

‎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")

نود جی اس

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

پی اچ پی

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

}

دات نت

‎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 محدود شده استفاده می‌کند که به کاربران امکان مشاهده و مدیریت تمام فایل‌های درایو شما را می‌دهد. برای کسب اطلاعات بیشتر در مورد محدوده‌های درایو، به «انتخاب محدوده‌های API گوگل درایو» مراجعه کنید.

این نمونه کد همچنین نوع MIME خروجی را application/pdf اعلام می‌کند. برای مشاهده لیست کاملی از تمام انواع MIME خروجی پشتیبانی شده برای هر سند Google Workspace، به Export MIME types for Google Workspace documents مراجعه کنید.

محتوای سند Google Workspace را در یک مرورگر صادر کنید

برای خروجی گرفتن از محتوای سند Google Workspace در مرورگر، از فیلد exportLinks در منبع files استفاده کنید. بسته به نوع سند، برای هر نوع MIME موجود، لینکی برای دانلود فایل و محتوای آن برگردانده می‌شود. می‌توانید کاربر را به یک URL هدایت کنید یا آن را به عنوان یک لینک قابل کلیک ارائه دهید.

محتوای سند Google Workspace را در نسخه قبلی مرورگر صادر کنید

برای خروجی گرفتن از محتوای سند Google Workspace در نسخه‌های قدیمی‌تر در مرورگر، از متد revisions.get به همراه شناسه فایل مورد نظر برای دانلود و شناسه نسخه اصلاح‌شده استفاده کنید تا یک لینک خروجی ایجاد شود که بتوانید از طریق آن دانلود را انجام دهید. اگر کاربر دسترسی دانلود به فایل را داشته باشد، لینکی برای دانلود فایل و محتویات آن برگردانده می‌شود. می‌توانید کاربر را به این URL هدایت کنید یا آن را به عنوان یک لینک قابل کلیک ارائه دهید.

محتوای سند Google Workspace را در طول عملیات طولانی مدت صادر کنید

برای خروجی گرفتن از محتوای سند Google Workspace در طول عملیات طولانی مدت، از متد files.download به همراه شناسه فایل مورد نظر برای دانلود و شناسه نسخه اصلاح شده استفاده کنید. برای اطلاعات بیشتر، به مدیریت عملیات طولانی مدت مراجعه کنید.

محدود کردن نحوه اشتراک‌گذاری فایل‌ها