本文說明如何使用 Google Picker API 功能,例如開啟多選、隱藏導覽窗格,以及使用應用程式目前的 OAuth 2.0 權杖選擇使用者帳戶。
必要條件
在本範例中,您需要指定多個項目:
如要找出「用戶端 ID」和「API 金鑰」,請按照下列步驟操作:
在 Google Cloud 控制台中,依序前往「選單」 >「API 和服務」 >「憑證」。
如要找出應用程式 ID,請按照下列步驟操作:
在 Google Cloud 控制台中,依序前往「選單」 >「IAM 與管理」 >「設定」。
請使用專案編號做為應用程式 ID。
用戶端 ID 和應用程式 ID 必須位於同一個 Google Cloud 專案中,因為系統會使用該專案授權存取使用者的檔案。
在 HTML 文件中建立圖片選取器應用程式
下列程式碼範例說明如何使用圖片選取器或上傳頁面,讓使用者透過網頁應用程式中的按鈕開啟。
建立標準 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:您在授權網頁應用程式的 OAuth 2.0 憑證時建立的用戶端 ID。
- API_KEY:您建立的 API 金鑰憑證。
- APP_ID:Google Cloud 專案的專案編號。
應用程式可透過 setOAuthToken 函式使用目前的驗證權杖,判斷 Google 挑選工具要使用哪個 Google 帳戶顯示檔案。如果使用者登入了多個 Google 帳戶,Google 挑選器可以顯示適當授權帳戶的檔案。
關閉 HTML 文件:
</body>
</html>
在開啟檔案時從 Google Picker 取得檔案 ID 後,應用程式就能擷取檔案中繼資料,並下載檔案內容,如 files 資源的 get 方法所述。
建立圖片選取器物件
以下程式碼範例顯示建構、算繪及處理 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);
}
}
更改下列內容: