वेब ऐप्लिकेशन के लिए कोड सैंपल

इस गाइड में, Google Picker API की सुविधाओं को इस्तेमाल करने का तरीका बताया गया है. जैसे, एक से ज़्यादा आइटम चुनने की सुविधा चालू करना, नेविगेशन पैन छिपाना, और ऐप्लिकेशन के मौजूदा OAuth 2.0 टोकन के साथ उपयोगकर्ता खाता चुनना.

ज़रूरी शर्तें

इस उदाहरण के लिए, आपको कई आइटम तय करने होंगे:

  • क्लाइंट आईडी और एपीआई पासकोड, दोनों को ढूंढने के लिए:

    1. Google Cloud console में, मेन्यू > एपीआई और सेवाएं > क्रेडेंशियल पर जाएं.

      क्रेडेंशियल पर जाएं

  • ऐप्लिकेशन आईडी ढूंढने के लिए:

    1. Google Cloud console में, मेन्यू > IAM और एडमिन > सेटिंग पर जाएं.

      'सेटिंग' पर जाएं

    2. ऐप्लिकेशन आईडी के लिए प्रोजेक्ट नंबर का इस्तेमाल करें.

एक ही Google Cloud प्रोजेक्ट में क्लाइंट आईडी और ऐप्लिकेशन आईडी, दोनों होने चाहिए. ऐसा इसलिए, क्योंकि इसका इस्तेमाल उपयोगकर्ता की फ़ाइलों का ऐक्सेस देने के लिए किया जाता है.

ऐप्लिकेशन बनाना

यहां दिए गए कोड सैंपल में, इमेज चुनने वाले टूल या अपलोड पेज का इस्तेमाल करने का तरीका बताया गया है. उपयोगकर्ता, वेब ऐप्लिकेशन में मौजूद बटन से इसे खोल सकते हैं.

drive/picker/helloworld.html
<!DOCTYPE html>
<html>
<head>
  <title>Google Picker API Quickstart</title>
  <meta charset="utf-8" />
</head>
<body>
<p>Google Picker API Quickstart</p>

<!--Add buttons to initiate auth sequence and sign out.-->
<button id="authorize_button" onclick="handleAuthClick()">Authorize</button>
<button id="signout_button" onclick="handleSignoutClick()">Sign Out</button>

<pre id="content" style="white-space: pre-wrap;"></pre>

<script type="text/javascript">
  /* exported gapiLoaded */
  /* exported gisLoaded */
  /* exported handleAuthClick */
  /* exported handleSignoutClick */

  // Authorization scopes required by the API; multiple scopes can be
  // included, separated by spaces.
  const SCOPES = 'https://www.googleapis.com/auth/drive.metadata.readonly';

  // TODO(developer): Replace with your client ID and API key from https://console.cloud.google.com/.
  const CLIENT_ID = '<YOUR_CLIENT_ID>';
  const API_KEY = '<YOUR_API_KEY>';

  // TODO(developer): Replace with your project number from https://console.cloud.google.com/.
  const APP_ID = '<YOUR_APP_ID>';

  let tokenClient;
  let accessToken = null;
  let pickerInited = false;
  let gisInited = false;

  document.getElementById('authorize_button').style.visibility = 'hidden';
  document.getElementById('signout_button').style.visibility = 'hidden';

  /**
   * Callback after api.js is loaded.
   */
  function gapiLoaded() {
    gapi.load('client:picker', initializePicker);
  }

  /**
   * Callback after the API client is loaded. Loads the
   * discovery doc to initialize the API.
   */
  async function initializePicker() {
    await gapi.client.load('https://www.googleapis.com/discovery/v1/apis/drive/v3/rest');
    pickerInited = true;
    maybeEnableButtons();
  }

  /**
   * Callback after Google Identity Services are loaded.
   */
  function gisLoaded() {
    tokenClient = google.accounts.oauth2.initTokenClient({
      client_id: CLIENT_ID,
      scope: SCOPES,
      callback: '', // defined later
    });
    gisInited = true;
    maybeEnableButtons();
  }

  /**
   * Enables user interaction after all libraries are loaded.
   */
  function maybeEnableButtons() {
    if (pickerInited && gisInited) {
      document.getElementById('authorize_button').style.visibility = 'visible';
    }
  }

  /**
   *  Sign in the user upon button click.
   */
  function handleAuthClick() {
    tokenClient.callback = async (response) => {
      if (response.error !== undefined) {
        throw (response);
      }
      accessToken = response.access_token;
      document.getElementById('signout_button').style.visibility = 'visible';
      document.getElementById('authorize_button').innerText = 'Refresh';
      await createPicker();
    };

    if (accessToken === null) {
      // Prompt the user to select a Google Account and ask for consent to share their data
      // when establishing a new session.
      tokenClient.requestAccessToken({prompt: 'consent'});
    } else {
      // Skip display of account chooser and consent dialog for an existing session.
      tokenClient.requestAccessToken({prompt: ''});
    }
  }

  /**
   *  Sign out the user upon button click.
   */
  function handleSignoutClick() {
    if (accessToken) {
      google.accounts.oauth2.revoke(accessToken);
      accessToken = null;
      document.getElementById('content').innerText = '';
      document.getElementById('authorize_button').innerText = 'Authorize';
      document.getElementById('signout_button').style.visibility = 'hidden';
    }
  }

  /**
   *  Create and render a Google Picker object for searching images.
   */
  function createPicker() {
    const view = new google.picker.View(google.picker.ViewId.DOCS);
    view.setMimeTypes('image/png,image/jpeg,image/jpg');
    const picker = new google.picker.PickerBuilder()
        .enableFeature(google.picker.Feature.NAV_HIDDEN)
        .enableFeature(google.picker.Feature.MULTISELECT_ENABLED)
        .setDeveloperKey(API_KEY)
        .setAppId(APP_ID)
        .setOAuthToken(accessToken)
        .addView(view)
        .addView(new google.picker.DocsUploadView())
        .setCallback(pickerCallback)
        .build();
    picker.setVisible(true);
  }

  /**
   * Displays the file details of the user's selection.
   * @param {object} data - Contains the user selection from the Google Picker.
   */
  async function pickerCallback(data) {
    if (data.action === google.picker.Action.PICKED) {
      let text = `Google Picker response: \n${JSON.stringify(data, null, 2)}\n`;
      const document = data[google.picker.Response.DOCUMENTS][0];
      const fileId = document[google.picker.Document.ID];
      console.log(fileId);
      const res = await gapi.client.drive.files.get({
        'fileId': fileId,
        'fields': '*',
      });
      text += `Drive API response for first document: \n${JSON.stringify(res.result, null, 2)}\n`;
      window.document.getElementById('content').innerText = text;
    }
  }
</script>
<script async defer src="https://apis.google.com/js/api.js" onload="gapiLoaded()"></script>
<script async defer src="https://accounts.google.com/gsi/client" onload="gisLoaded()"></script>
</body>
</html>

setOAuthToken फ़ंक्शन की मदद से, कोई ऐप्लिकेशन मौजूदा पुष्टि करने वाले टोकन का इस्तेमाल कर सकता है. इससे यह तय किया जा सकता है कि Google Picker, फ़ाइलें दिखाने के लिए किस Google खाते का इस्तेमाल करेगा. अगर किसी उपयोगकर्ता ने एक से ज़्यादा Google खातों से साइन इन किया है, तो Google Picker, अनुमति वाले सही खाते की फ़ाइलें दिखा सकता है.

फ़ाइलें खोलते समय, Google Picker से फ़ाइल आईडी पाने के बाद, कोई ऐप्लिकेशन फ़ाइल का मेटाडेटा फ़ेच कर सकता है. साथ ही, files संसाधन के get तरीके में बताए गए तरीके से, फ़ाइल का कॉन्टेंट डाउनलोड कर सकता है.