फ़ाइलें डाउनलोड और एक्सपोर्ट करना

Google Drive API, कई तरह की डाउनलोड और एक्सपोर्ट से जुड़ी कार्रवाइयों का इस्तेमाल करता है, जैसा कि इस टेबल में बताया गया है:

वीडियो डाउनलोड करने की सुविधा
alt=media यूआरएल पैरामीटर के साथ files.get तरीके का इस्तेमाल करके ब्लॉब फ़ाइल का कॉन्टेंट.
alt=media यूआरएल पैरामीटर के साथ revisions.get तरीके का इस्तेमाल करके, पहले के वर्शन में मौजूद ब्लॉब फ़ाइल का कॉन्टेंट.
webContentLink फ़ील्ड का इस्तेमाल करके ब्राउज़र में Blob फ़ाइल का कॉन्टेंट.
एक्सपोर्ट
Google Workspace के दस्तावेज़ का कॉन्टेंट ऐसे फ़ॉर्मैट में होना चाहिए जिसे आपका ऐप्लिकेशन मैनेज कर सके. इसके लिए, files.export का इस्तेमाल किया जाता है.
exportLinks फ़ील्ड का इस्तेमाल करके, ब्राउज़र में Google Workspace दस्तावेज़ का कॉन्टेंट.
exportLinks फ़ील्ड का इस्तेमाल करके, ब्राउज़र में Google Workspace के दस्तावेज़ के कॉन्टेंट का पुराना वर्शन इस्तेमाल किया जा सकता है.

फ़ाइल का कॉन्टेंट डाउनलोड या एक्सपोर्ट करने से पहले, पुष्टि करें कि उपयोगकर्ता files संसाधन पर मौजूद capabilities.canDownload फ़ील्ड का इस्तेमाल करके फ़ाइल डाउनलोड कर सकते हैं.

इस गाइड के बाकी हिस्से में, इस तरह की डाउनलोड और एक्सपोर्ट कार्रवाइयों के लिए पूरी जानकारी दी गई है.

blob फ़ाइल का कॉन्टेंट डाउनलोड करें

Drive में सेव की गई blob फ़ाइल डाउनलोड करने के लिए, डाउनलोड करने के लिए फ़ाइल के आईडी और alt=media यूआरएल पैरामीटर के साथ, files.get तरीके का इस्तेमाल करें. alt=media यूआरएल पैरामीटर, सर्वर को बताता है कि कॉन्टेंट को डाउनलोड करने का अनुरोध, रिस्पॉन्स के वैकल्पिक फ़ॉर्मैट के तौर पर किया जा रहा है.

alt=media यूआरएल पैरामीटर एक सिस्टम पैरामीटर है. यह सभी Google REST API में उपलब्ध होता है. अगर Drive API के लिए क्लाइंट लाइब्रेरी का इस्तेमाल किया जाता है, तो आपको इस पैरामीटर को साफ़ तौर पर सेट करने की ज़रूरत नहीं है.

नीचे दिया गया कोड सैंपल, Drive API क्लाइंट लाइब्रेरी से फ़ाइल डाउनलोड करने के लिए, files.get तरीके का इस्तेमाल करने का तरीका दिखाता है.

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
/**
 * 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 यूआरएल पैरामीटर जोड़ता है.

आपके ऐप्लिकेशन से शुरू की गई फ़ाइल को ऐसे दायरे में होना चाहिए जिससे फ़ाइल के कॉन्टेंट को पढ़ने की अनुमति मिल सके. उदाहरण के लिए, drive.readonly.metadata दायरे का इस्तेमाल करने वाले ऐप्लिकेशन को फ़ाइल का कॉन्टेंट डाउनलोड करने की अनुमति नहीं होती. कोड का यह नमूना, “drive” फ़ाइल के उस स्कोप का इस्तेमाल करता है जिससे उपयोगकर्ता, Drive में मौजूद आपकी सभी फ़ाइलों को देख सकते हैं और उन्हें मैनेज कर सकते हैं. Drive के स्कोप के बारे में ज़्यादा जानने के लिए, Google Drive API के दायरे चुनना लेख पढ़ें.

जिन उपयोगकर्ताओं के पास बदलाव करने की अनुमतियां हैं वे copyRequiresWriterPermission फ़ील्ड को false पर सेट करके, रीड-ओनली उपयोगकर्ताओं को डाउनलोड करने से रोक सकते हैं.

आपत्तिजनक (जैसे कि नुकसान पहुंचाने वाला सॉफ़्टवेयर) के तौर पर पहचानी गई फ़ाइलों को सिर्फ़ फ़ाइल का मालिक ही डाउनलोड कर सकता है. इसके अलावा, get क्वेरी पैरामीटर acknowledgeAbuse=true को यह बताने के लिए शामिल किया जाना चाहिए कि उपयोगकर्ता ने संभावित रूप से अनचाहे सॉफ़्टवेयर या बुरे बर्ताव वाली दूसरी फ़ाइलों को डाउनलोड करने के जोखिम को स्वीकार किया है. आपके ऐप्लिकेशन को इस क्वेरी पैरामीटर का इस्तेमाल करने से पहले उपयोगकर्ता को इंटरैक्टिव तरीके से चेतावनी देनी चाहिए.

आंशिक डाउनलोड

कुछ हद तक डाउनलोड होने में, फ़ाइल का सिर्फ़ एक तय हिस्सा डाउनलोड होता है. आपके पास फ़ाइल का वह हिस्सा तय करने का विकल्प होता है जिसे आपको डाउनलोड करना है. इसके लिए, Range हेडर के साथ बाइट रेंज का इस्तेमाल करें. उदाहरण के लिए:

Range: bytes=500-999

blob फ़ाइल का कॉन्टेंट पहले के वर्शन में डाउनलोड करना

ब्लॉब फ़ाइलों का कॉन्टेंट डाउनलोड करने के लिए, डाउनलोड किए जाने वाले फ़ाइल आईडी, बदलाव के आईडी, और alt=media यूआरएल पैरामीटर के साथ revisions.get तरीके का इस्तेमाल करें. alt=media यूआरएल पैरामीटर, सर्वर को बताता है कि कॉन्टेंट को डाउनलोड करने का अनुरोध, रिस्पॉन्स के वैकल्पिक फ़ॉर्मैट के तौर पर किया जा रहा है. files.get की तरह ही, revisions.get वाला तरीका भी वैकल्पिक क्वेरी पैरामीटर acknowledgeAbuse और Range हेडर के साथ काम करता है. बदलावों को डाउनलोड करने के बारे में ज़्यादा जानने के लिए, फ़ाइल में हुए बदलाव डाउनलोड और पब्लिश करना देखें.

ब्राउज़र में blob फ़ाइल का कॉन्टेंट डाउनलोड करना

Drive पर सेव की गई blob फ़ाइलों का कॉन्टेंट किसी ब्राउज़र में डाउनलोड करने के लिए, एपीआई के बजाय, files संसाधन के webContentLink फ़ील्ड का इस्तेमाल करें. अगर उपयोगकर्ता के पास फ़ाइल को डाउनलोड करने का ऐक्सेस है, तो फ़ाइल और उसका कॉन्टेंट डाउनलोड करने का लिंक दिखता है. उपयोगकर्ता को इस यूआरएल पर रीडायरेक्ट किया जा सकता है या उसे क्लिक किए जा सकने वाले लिंक के तौर पर दिखाया जा सकता है.

Google Workspace दस्तावेज़ का कॉन्टेंट एक्सपोर्ट करें

Google Workspace के दस्तावेज़ बाइट कॉन्टेंट को एक्सपोर्ट करने के लिए, फ़ाइल के आईडी के साथ files.export तरीके और सही MIME टाइप का इस्तेमाल करें. एक्सपोर्ट किया गया कॉन्टेंट 10 एमबी तक हो सकता है.

नीचे दिया गया कोड सैंपल, Drive API क्लाइंट लाइब्रेरी का इस्तेमाल करके, Google Workspace दस्तावेज़ को PDF फ़ॉर्मैट में एक्सपोर्ट करने के लिए, files.export तरीके का इस्तेमाल करने का तरीका बताता है:

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
/**
 * 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 के स्कोप के बारे में ज़्यादा जानने के लिए, Google Drive API के दायरे चुनना लेख पढ़ें.

कोड सैंपल, एक्सपोर्ट MIME टाइप को भी application/pdf के तौर पर बताता है. Google Workspace के हर दस्तावेज़ में काम करने वाले, एक्सपोर्ट MIME टाइप की पूरी सूची देखने के लिए, Google Workspace के दस्तावेज़ों के लिए MIME टाइप एक्सपोर्ट करें देखें.

Google Workspace दस्तावेज़ के कॉन्टेंट को ब्राउज़र में एक्सपोर्ट करना

किसी ब्राउज़र में Google Workspace के दस्तावेज़ का कॉन्टेंट एक्सपोर्ट करने के लिए, files संसाधन के exportLinks फ़ील्ड का इस्तेमाल करें. दस्तावेज़ किस तरह का है, इस पर निर्भर करते हुए, फ़ाइल और उसकी सामग्री को डाउनलोड करने का लिंक हर उपलब्ध MIME टाइप के लिए दिखाया जाता है. उपयोगकर्ता को यूआरएल पर रीडायरेक्ट किया जा सकता है या उसे क्लिक किए जा सकने वाले लिंक के तौर पर दिखाया जा सकता है.

Google Workspace दस्तावेज़ के कॉन्टेंट को ब्राउज़र में, किसी पुराने वर्शन पर एक्सपोर्ट करना

Google Workspace दस्तावेज़ के कॉन्टेंट को किसी ब्राउज़र में पहले के वर्शन में एक्सपोर्ट करने के लिए, डाउनलोड की जाने वाली फ़ाइल का आईडी और बदलाव के आईडी के साथ, revisions.get तरीके का इस्तेमाल करें. अगर उपयोगकर्ता के पास फ़ाइल को डाउनलोड करने का ऐक्सेस है, तो फ़ाइल और उसका कॉन्टेंट डाउनलोड करने का लिंक दिखता है. उपयोगकर्ता को इस यूआरएल पर रीडायरेक्ट किया जा सकता है या उसे क्लिक किए जा सकने वाले लिंक के तौर पर दिखाया जा सकता है.