Sử dụng bộ sưu tập để sắp xếp ngăn nắp các trang
Lưu và phân loại nội dung dựa trên lựa chọn ưu tiên của bạn.
Mã mẫu sau đây cho biết cách sử dụng bộ chọn hình ảnh hoặc trang tải lên mà người dùng có thể mở từ một nút trong ứng dụng web.
Ví dụ này kết hợp các tính năng của Bộ chọn Google, chẳng hạn như bật tính năng chọn nhiều mục, ẩn ngăn điều hướng và chọn tài khoản người dùng bằng mã OAuth 2.0 hiện tại của ứng dụng.
Đối với ví dụ này, bạn cần chỉ định một số mục:
Cách tìm cả Mã ứng dụng và Khoá API:
Trong Google Cloud Console, hãy chuyển đến Trình đơn
menu>API và dịch vụ>Thông tin xác thực.
<!DOCTYPE html>
<html>
<head>
<title>Picker API Quickstart</title>
<meta charset="utf-8" />
</head>
<body>
<p>Picker API 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): Set to client ID and API key from the Developer Console
const CLIENT_ID = '<YOUR_CLIENT_ID>';
const API_KEY = '<YOUR_API_KEY>';
// TODO(developer): Replace with your own project number from console.developers.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 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 - Containers the user selection from the picker
*/
async function pickerCallback(data) {
if (data.action === google.picker.Action.PICKED) {
let text = `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>
Hàm setOAuthToken cho phép ứng dụng sử dụng mã thông báo xác thực hiện tại để xác định Tài khoản Google mà Công cụ chọn của Google sử dụng để hiển thị các tệp.
Nếu người dùng đăng nhập bằng nhiều Tài khoản Google, thì Công cụ chọn của Google có thể hiển thị các tệp của tài khoản được uỷ quyền thích hợp.
Sau khi lấy mã tệp từ Google Picker khi mở tệp, ứng dụng có thể tìm nạp siêu dữ liệu tệp và tải nội dung tệp xuống như mô tả trong tài liệu tham khảo cho files.get.
[[["Dễ hiểu","easyToUnderstand","thumb-up"],["Giúp tôi giải quyết được vấn đề","solvedMyProblem","thumb-up"],["Khác","otherUp","thumb-up"]],[["Thiếu thông tin tôi cần","missingTheInformationINeed","thumb-down"],["Quá phức tạp/quá nhiều bước","tooComplicatedTooManySteps","thumb-down"],["Đã lỗi thời","outOfDate","thumb-down"],["Vấn đề về bản dịch","translationIssue","thumb-down"],["Vấn đề về mẫu/mã","samplesCodeIssue","thumb-down"],["Khác","otherDown","thumb-down"]],["Cập nhật lần gần đây nhất: 2025-01-23 UTC."],[[["This code sample demonstrates how to integrate Google Picker into a web app, allowing users to select or upload images using their Google Drive."],["It utilizes Google Picker features like multi-select, hiding navigation, and leveraging the app's OAuth 2.0 token for user authorization."],["Before running the code, you need to locate your Client ID, API Key, and App ID from the Google Cloud Console."],["The sample code provides functionalities for user authorization, sign-out, and displaying selected file details."]]],[]]