Пример кода для веб-приложений
Оптимизируйте свои подборки
Сохраняйте и классифицируйте контент в соответствии со своими настройками.
В этом руководстве объясняется, как использовать функции API Google Picker, такие как включение множественного выбора, скрытие панели навигации и выбор учетной записи пользователя с текущим токеном OAuth 2.0 приложения.
Предпосылки
Для этого примера вам необходимо указать несколько пунктов:
Один и тот же проект Google Cloud должен содержать как идентификатор клиента, так и идентификатор приложения, поскольку он используется для авторизации доступа к файлам пользователя.
Создать приложение
В следующем примере кода показано, как использовать селектор изображений или страницу загрузки, которую пользователи могут открыть с помощью кнопки в веб-приложении.
Функция setOAuthToken
позволяет приложению использовать текущий токен авторизации для определения учётной записи Google, которую Google Picker использует для отображения файлов. Если пользователь вошел в систему с несколькими учётными записями Google, Google Picker может отображать файлы соответствующей авторизованной учётной записи.
Получив идентификатор файла из Google Picker при открытии файлов, приложение может извлечь метаданные файла и загрузить содержимое файла, как описано в методе get
ресурса files
.
Если не указано иное, контент на этой странице предоставляется по лицензии Creative Commons "С указанием авторства 4.0", а примеры кода – по лицензии Apache 2.0. Подробнее об этом написано в правилах сайта. Java – это зарегистрированный товарный знак корпорации Oracle и ее аффилированных лиц.
Последнее обновление: 2025-08-29 UTC.
[null,null,["Последнее обновление: 2025-08-29 UTC."],[],[],null,["# Code sample for web apps\n\nThis guide explains how to use Google Picker API features such as turning on\nmulti-select, hiding the navigation pane, and choosing the user account with the\napp's current OAuth 2.0 token.\n| **Note:** You can also use the [`@googleworkspace/drive-picker-element`](https://npmjs.com/package/@googleworkspace/drive-picker-element) web component to integrate the Google Picker into your web app.\n\nPrerequisites\n-------------\n\nFor this example, you need to specify several items:\n\n- To locate both the **Client ID** and the **API Key**:\n\n 1. In the Google Cloud console, go to Menu\n menu\n \\\u003e **APIs \\& Services**\n \\\u003e **Credentials**.\n\n [Go to Credentials](https://console.cloud.google.com/apis/credentials)\n- To locate the **App ID**:\n\n 1. In the Google Cloud console, go to Menu\n menu\n \\\u003e **IAM \\& Admin**\n \\\u003e **Settings**.\n\n [Go to Settings](https://console.cloud.google.com/iam-admin/settings)\n 2. Use the **project number** for the app ID.\n\nThe same Google Cloud project must contain both the client ID and the app ID as it's\nused to authorize access to a user's files.\n\nCreate the app\n--------------\n\nThe following code sample shows how to use an image selector or upload page that\nusers can open from a button in a web app. \ndrive/picker/helloworld.html \n[View on GitHub](https://github.com/googleworkspace/browser-samples/blob/main/drive/picker/helloworld.html) \n\n```html\n\u003c!DOCTYPE html\u003e\n\u003chtml\u003e\n\u003chead\u003e\n \u003ctitle\u003eGoogle Picker API Quickstart\u003c/title\u003e\n \u003cmeta charset=\"utf-8\" /\u003e\n\u003c/head\u003e\n\u003cbody\u003e\n\u003cp\u003eGoogle Picker API Quickstart\u003c/p\u003e\n\n\u003c!--Add buttons to initiate auth sequence and sign out.--\u003e\n\u003cbutton id=\"authorize_button\" onclick=\"handleAuthClick()\"\u003eAuthorize\u003c/button\u003e\n\u003cbutton id=\"signout_button\" onclick=\"handleSignoutClick()\"\u003eSign Out\u003c/button\u003e\n\n\u003cpre id=\"content\" style=\"white-space: pre-wrap;\"\u003e\u003c/pre\u003e\n\n\u003cscript type=\"text/javascript\"\u003e\n /* exported gapiLoaded */\n /* exported gisLoaded */\n /* exported handleAuthClick */\n /* exported handleSignoutClick */\n\n // Authorization scopes required by the API; multiple scopes can be\n // included, separated by spaces.\n const SCOPES = 'https://www.googleapis.com/auth/drive.metadata.readonly';\n\n // TODO(developer): Replace with your client ID and API key from https://console.cloud.google.com/.\n const CLIENT_ID = '\u003cYOUR_CLIENT_ID\u003e';\n const API_KEY = '\u003cYOUR_API_KEY\u003e';\n\n // TODO(developer): Replace with your project number from https://console.cloud.google.com/.\n const APP_ID = '\u003cYOUR_APP_ID\u003e';\n\n let tokenClient;\n let accessToken = null;\n let pickerInited = false;\n let gisInited = false;\n\n document.getElementById('authorize_button').style.visibility = 'hidden';\n document.getElementById('signout_button').style.visibility = 'hidden';\n\n /**\n * Callback after api.js is loaded.\n */\n function gapiLoaded() {\n gapi.load('client:picker', initializePicker);\n }\n\n /**\n * Callback after the API client is loaded. Loads the\n * discovery doc to initialize the API.\n */\n async function initializePicker() {\n await gapi.client.load('https://www.googleapis.com/discovery/v1/apis/drive/v3/rest');\n pickerInited = true;\n maybeEnableButtons();\n }\n\n /**\n * Callback after Google Identity Services are loaded.\n */\n function gisLoaded() {\n tokenClient = google.accounts.oauth2.initTokenClient({\n client_id: CLIENT_ID,\n scope: SCOPES,\n callback: '', // defined later\n });\n gisInited = true;\n maybeEnableButtons();\n }\n\n /**\n * Enables user interaction after all libraries are loaded.\n */\n function maybeEnableButtons() {\n if (pickerInited && gisInited) {\n document.getElementById('authorize_button').style.visibility = 'visible';\n }\n }\n\n /**\n * Sign in the user upon button click.\n */\n function handleAuthClick() {\n tokenClient.callback = async (response) =\u003e {\n if (response.error !== undefined) {\n throw (response);\n }\n accessToken = response.access_token;\n document.getElementById('signout_button').style.visibility = 'visible';\n document.getElementById('authorize_button').innerText = 'Refresh';\n await createPicker();\n };\n\n if (accessToken === null) {\n // Prompt the user to select a Google Account and ask for consent to share their data\n // when establishing a new session.\n tokenClient.requestAccessToken({prompt: 'consent'});\n } else {\n // Skip display of account chooser and consent dialog for an existing session.\n tokenClient.requestAccessToken({prompt: ''});\n }\n }\n\n /**\n * Sign out the user upon button click.\n */\n function handleSignoutClick() {\n if (accessToken) {\n google.accounts.oauth2.revoke(accessToken);\n accessToken = null;\n document.getElementById('content').innerText = '';\n document.getElementById('authorize_button').innerText = 'Authorize';\n document.getElementById('signout_button').style.visibility = 'hidden';\n }\n }\n\n /**\n * Create and render a Google Picker object for searching images.\n */\n function createPicker() {\n const view = new google.picker.View(google.picker.ViewId.DOCS);\n view.setMimeTypes('image/png,image/jpeg,image/jpg');\n const picker = new google.picker.PickerBuilder()\n .enableFeature(google.picker.Feature.NAV_HIDDEN)\n .enableFeature(google.picker.Feature.MULTISELECT_ENABLED)\n .setDeveloperKey(API_KEY)\n .setAppId(APP_ID)\n .setOAuthToken(accessToken)\n .addView(view)\n .addView(new google.picker.DocsUploadView())\n .setCallback(pickerCallback)\n .build();\n picker.setVisible(true);\n }\n\n /**\n * Displays the file details of the user's selection.\n * @param {object} data - Contains the user selection from the Google Picker.\n */\n async function pickerCallback(data) {\n if (data.action === google.picker.Action.PICKED) {\n let text = `Google Picker response: \\n${JSON.stringify(data, null, 2)}\\n`;\n const document = data[google.picker.Response.DOCUMENTS][0];\n const fileId = document[google.picker.Document.ID];\n console.log(fileId);\n const res = await gapi.client.drive.files.get({\n 'fileId': fileId,\n 'fields': '*',\n });\n text += `Drive API response for first document: \\n${JSON.stringify(res.result, null, 2)}\\n`;\n window.document.getElementById('content').innerText = text;\n }\n }\n\u003c/script\u003e\n\u003cscript async defer src=\"https://apis.google.com/js/api.js\" onload=\"gapiLoaded()\"\u003e\u003c/script\u003e\n\u003cscript async defer src=\"https://accounts.google.com/gsi/client\" onload=\"gisLoaded()\"\u003e\u003c/script\u003e\n\u003c/body\u003e\n\u003c/html\u003e\n```\n\nThe `setOAuthToken` function allows an app to use the current auth token to\ndetermine which Google Account the Google Picker uses to display the files. If\na user is signed in with multiple Google Accounts, the Google Picker can\ndisplay the files of the appropriate authorized account.\n\nAfter obtaining the file ID from the Google Picker when opening files, an app\ncan then fetch the file metadata and download the file content as described in\nthe [`get`](/workspace/drive/api/reference/rest/v3/files/get) method of the [`files`](/workspace/drive/api/reference/rest/v3/files) resource."]]