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

Google Drive API از چندین نوع اقدام بارگیری و صادرات پشتیبانی می کند که در جدول زیر فهرست شده است:

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

قبل از دانلود یا صادر کردن محتوای فایل، بررسی کنید که کاربران می توانند فایل را با استفاده از قسمت capabilities.canDownload در منبع files دانلود کنند.

بقیه این راهنما دستورالعمل های دقیقی را برای انجام این نوع اقدامات دانلود و صادرات ارائه می دهد.

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

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

پارامتر alt=media URL یک پارامتر سیستمی است که در همه APIهای Google 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")

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

}

.خالص

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، به انتخاب حوزه‌های API Google Drive مراجعه کنید.

کاربران دارای مجوز ویرایش می توانند با تنظیم فیلد copyRequiresWriterPermission بر روی false ، دانلود توسط کاربران فقط خواندنی را محدود کنند.

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

دانلود جزئی

دانلود جزئی شامل دانلود تنها بخش مشخصی از یک فایل است. با استفاده از محدوده بایت با سربرگ 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 صحیح استفاده کنید. محتوای صادر شده به 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")

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

}

.خالص

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 Google 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 هدایت کنید یا آن را به عنوان یک پیوند قابل کلیک ارائه دهید.