Ce document explique comment utiliser les fonctionnalités de l'API Google Picker, comme l'activation de la sélection multiple, le masquage du volet de navigation et le choix du compte utilisateur avec le jeton OAuth 2.0 actuel de l'application.
Prérequis
Pour cet exemple, vous devez configurer les éléments suivants dans votre projet Google Cloud :
Activer les API : activez à la fois l'API Google Picker et l' API Google Drive :
Dans la console Google Cloud, accédez à Menu > API et services > Bibliothèque.
Recherchez et activez l'API Google Picker et l'API Google Drive.
Créer une clé API :
Dans la console Google Cloud, accédez à Menu > API et services > Identifiants.
Cliquez sur Créer des identifiants > Clé API.
(Recommandé) Pour sécuriser votre clé API avec des restrictions, cliquez sur Modifier la clé API:
Restrictions liées aux applications : sous Définir une restriction d'application , sélectionnez Sites Web. Sous Restrictions liées aux sites Web, ajoutez l'origine de votre application (par exemple,
https://example.com/*ouhttp://localhost/*) ethttps://docs.google.com/*à la liste des sites Web spécifiés. Étant donné que le sélecteur Google s'affiche dans un iframe hébergé surdocs.google.com, les requêtes échouent avec une erreurAPI developer key is invalidsihttps://docs.google.com/*n'est pas autorisé.Restrictions d'API : sous Restrictions d'API, sélectionnez Restreindre la clé, puis sélectionnez l'API Google Picker et l' API Google Drive.
Créer un ID client OAuth 2.0 :
Dans la console Google Cloud, accédez à Menu > API et services > Identifiants.
Cliquez sur Créer des identifiants > ID client OAuth.
Sélectionnez Application Web et ajoutez vos origines JavaScript autorisées.
Rechercher l'ID d'application :
Dans la console Google Cloud, accédez à Menu > IAM et administration > Paramètres.
Utilisez le numéro de projet pour l'ID d'application.
Le même projet Google Cloud doit contenir à la fois l'ID client et l'ID d'application, car il est utilisé pour autoriser l'accès aux fichiers d'un utilisateur.
Créer une application de sélection d'images dans un document HTML
L'exemple de code suivant montre comment utiliser un sélecteur d'images ou une page d'importation que les utilisateurs peuvent ouvrir à partir d'un bouton dans une application Web.
Créez un document HTML standard pour héberger le sélecteur Google :
<!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>
Utilisez JavaScript pour appeler l'API Google Picker :
<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';
// Replace with your client ID and API key from https://console.cloud.google.com/.
const CLIENT_ID = 'CLIENT_ID';
const API_KEY = 'API_KEY';
// Replace with your project number from https://console.cloud.google.com/.
const APP_ID = '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 selectedDoc = data[google.picker.Response.DOCUMENTS][0];
const fileId = selectedDoc[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>
Remplacez les éléments suivants :
- CLIENT_ID : ID client que vous avez créé lorsque vous avez autorisé les identifiants OAuth 2.0 pour l' application Web.
- API_KEY : identifiants de clé API que vous avez créés.
- APP_ID : numéro de projet du projet Google Cloud.
La fonction setOAuthToken permet à une application d'utiliser le jeton d'authentification actuel pour déterminer le compte Google utilisé par le sélecteur Google pour afficher les fichiers. Si un utilisateur est connecté à plusieurs comptes Google, le sélecteur Google peut afficher les fichiers du compte autorisé approprié.
Fermez le document HTML :
</body>
</html>
Après avoir obtenu l'ID de fichier à partir du sélecteur Google lors de l'ouverture de fichiers,
une application peut ensuite récupérer les métadonnées du fichier et télécharger son contenu, comme
décrit dans la méthode get de la ressource
files.
Créer un objet de sélection d'images
L'exemple de code suivant montre la logique de base pour créer, afficher et gérer l'API Google Picker afin de créer un sélecteur d'images.
Utilisez JavaScript pour appeler l'API Google Picker :
/**
* Create and render a Google Picker object for searching images.
*/
function createPicker() {
// Define what types of files the Picker should show (e.g., images)
const view = new google.picker.View(google.picker.ViewId.DOCS);
view.setMimeTypes('image/png,image/jpeg,image/jpg');
// Build and display the picker.
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('ACCESS_TOKEN')
.addView(view)
.addView(new google.picker.DocsUploadView()) // Adds an upload tab
.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`;
// Extract the ID of the first selected document.
const selectedDoc = data[google.picker.Response.DOCUMENTS][0];
const fileId = selectedDoc[google.picker.Document.ID];
console.log("Selected File ID:", fileId);
// Optional: Fetch metadata using the Drive API based on the selected file ID.
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`;
// Update your UI with the results
console.log(text);
}
}
Remplacez les éléments suivants :
- API_KEY : identifiants de clé API que vous avez créés.
- APP_ID : numéro de projet du projet Google Cloud.
- ACCESS_TOKEN : jeton OAuth 2.0 de votre application.