本文档介绍了如何使用 Google Picker API 功能,例如启用多选、隐藏导航窗格,以及使用应用的当前 OAuth 2.0 令牌选择用户账号。
前提条件
对于此示例,您需要在 Google Cloud 云项目中配置以下内容:
启用 API: 同时启用 Google Picker API 和 Google Drive API:
在 Google Cloud 控制台中,依次前往菜单 > API 和服务 > 库。
搜索并启用 Google Picker API 和 Google Drive API 。
创建 API 密钥:
在 Google Cloud 控制台中,依次前往菜单 > API 和服务 > 凭据。
点击创建凭据 > API 密钥。
(推荐)如需使用限制保护 API 密钥,请点击 Edit API key:
应用限制:在设置应用 限制下,选择网站。在网站限制中,将应用的来源(例如
https://example.com/*或http://localhost/*)和https://docs.google.com/*添加到指定网站列表中。由于 Google Picker 在docs.google.com上托管的 iframe 中呈现,因此如果未允许https://docs.google.com/*,请求会失败并显示API developer key is invalid错误。API 限制:在 API 限制 下,选择 限制密钥,然后同时选择 Google Picker API 和 Google Drive API。
创建 OAuth 2.0 客户端 ID:
在 Google Cloud 控制台中,依次前往菜单 > API 和服务 > 凭据。
点击创建凭据 > OAuth 客户端 ID。
选择Web 应用 ,然后添加已获授权的 JavaScript 来源。
找到应用 ID:
在 Google Cloud 控制台中,依次前往菜单 > IAM 和管理 > 设置。
使用项目编号 作为应用 ID。
同一 Google Cloud 云项目必须同时包含客户端 ID 和应用 ID,因为它们用于授权访问用户的文件。
在 HTML 文档中创建图片选择器应用
以下代码示例展示了如何使用图片选择器或上传页面,用户可以从 Web 应用中的按钮打开该页面。
创建一个标准 HTML 文档来托管 Google Picker:
<!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>
使用 JavaScript 调用 Google Picker API:
<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>
替换以下内容:
- CLIENT_ID:您在为 Web 应用 授权 OAuth 2.0 凭据时创建的客户端 ID。
- API_KEY:您创建的 API 密钥 凭据 。
- APP_ID:Google Cloud 项目中的项目编号。
借助 setOAuthToken 函数,应用可以使用当前身份验证令牌来确定 Google Picker 使用哪个 Google 账号来显示文件。如果用户使用多个 Google 账号登录,Google Picker 可以显示相应已获授权账号的文件。
关闭 HTML 文档:
</body>
</html>
在打开文件时从 Google Picker 获取文件 ID 后,
应用便可以提取文件元数据并下载文件内容,如
get 方法中所述,该方法属于
files 资源。
创建图片选择器对象
以下代码示例展示了构建、呈现和处理 Google Picker API 以创建图片选择器的核心逻辑。
使用 JavaScript 调用 Google Picker API:
/**
* 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);
}
}
替换以下内容: