本指南說明 Google Drive API 支援的幾種檔案和資料夾搜尋方式。
您可以使用 files 資源的 list 方法,傳回雲端硬碟使用者的所有或部分檔案和資料夾。您也可以使用 list 方法,擷取部分資源方法 (例如 get 和 update 方法) 所需的 fileId。
使用 fields 參數
如要指定回應中傳回的欄位,可以使用 files 資源的任何方法,設定 fields 系統參數。如果省略 fields 參數,伺服器會傳回方法專屬的預設欄位組合。舉例來說,list 方法只會傳回每個檔案的 kind、id、name、mimeType 和 resourceKey 欄位。如要傳回其他欄位,請參閱「傳回特定欄位」。
依 ID 取得檔案
如要取得檔案,請在 files 資源上使用 get 方法,並提供 fileId 路徑參數。如果不知道檔案 ID,可以使用 list 方法列出所有檔案。
這個方法會以 files 資源例項的形式傳回檔案。如果提供 alt=media 參數,回應主體就會包含檔案內容。如要下載 Blob 檔案,請參閱「下載 Blob 檔案內容」。
如要確認下載已知惡意軟體或其他濫用檔案的風險,請將 acknowledgeAbuse 查詢參數設為 true。只有在設定 alt=media 參數,且使用者是檔案擁有者或檔案所在共用雲端硬碟的管理員時,這個欄位才適用。
列出「我的雲端硬碟」中的所有檔案和資料夾
使用不含任何參數的 list 方法,傳回目前使用者「我的雲端硬碟」中的所有檔案和資料夾。
下列 curl 指令顯示如何列出所有檔案:
curl -X GET \
'https://www.googleapis.com/drive/v3/files' \
-H 'Authorization: Bearer ACCESS_TOKEN' \
-H 'Accept: application/json'
將 ACCESS_TOKEN 替換為已授權的 OAuth 2.0 存取權杖。
在「我的雲端硬碟」中搜尋特定檔案和資料夾
如要搜尋目前使用者「我的雲端硬碟」中的特定檔案或資料夾,請使用 q 查詢字串欄位和 list 方法,並結合一或多個搜尋字詞來篩選要傳回的檔案。
查詢字串語法包含下列三個部分:
query_term operator values
其中:
query_term是要搜尋的查詢字詞或欄位。operator指定查詢字詞的條件。values是您要用來篩選搜尋結果的特定值。
舉例來說,下列查詢字串會設定 MIME 類型,將搜尋結果篩選為只傳回資料夾:
mimeType = 'application/vnd.google-apps.folder'
如要查看所有檔案查詢字詞,請參閱「檔案專屬查詢字詞」。
如要查看可用於建構查詢的所有查詢運算子,請參閱「查詢運算子」。
查詢字串範例
下表列出一些基本查詢字串的範例。實際程式碼會因您用於搜尋的用戶端程式庫而異。
您也必須逸出檔案名稱中的特殊字元,確保查詢能正常運作。舉例來說,如果檔案名稱同時包含單引號 (') 和反斜線 ("\") 字元,請使用反斜線逸出:name
contains 'quinn\'s paper\\essay'。
| 查詢內容 | 範例 |
|---|---|
字串比對運算子 (contains) |
|
| 含有「hello」字詞的檔案 | fullText contains 'hello' |
| 含有「hello world」確切詞組的檔案 | fullText contains '"hello world"' |
| 查詢中含有「\」字元的檔案 (例如「\authors」) | fullText contains '\\authors' |
| 名稱含有「預算」的檔案 | name contains 'budget' |
等式和不等式運算子 (=、!=) |
|
| 名稱為「hello」的檔案 | name = 'hello' |
| 資料夾 | mimeType = 'application/vnd.google-apps.folder' |
| 非資料夾的檔案 | mimeType != 'application/vnd.google-apps.folder' |
| 已加星號的檔案 | starred = true |
| 垃圾桶中的檔案 | trashed = true |
| 不在垃圾桶中的檔案 | trashed = false |
| 指向特定檔案 ID 的捷徑 | shortcutDetails.targetId = '1987654321' |
| 未與任何人或網域共用的檔案 (私人檔案,或與特定使用者或群組共用的檔案) | visibility = 'limited' |
| 知道連結的使用者皆可存取的檔案 | visibility = 'anyoneWithLink' |
| 可在網路上公開搜尋的檔案 | visibility = 'anyoneCanFind' |
比較運算子 (>、>=、<、<=) |
|
| 在指定日期後修改的檔案 (預設時區為世界標準時間) | modifiedTime > '2012-06-04T12:00:00' |
| 2023 年 1 月 1 日後建立的檔案 | createdTime > '2023-01-01T00:00:00' |
| 2023 年 1 月 1 日前修改的檔案 | modifiedTime < '2023-01-01T00:00:00' |
集合成員資格運算子 (in) |
|
集合中的直接子項檔案 (例如 parents 集合中的資料夾 ID) |
'1234567' in parents |
| 應用程式資料資料夾中的檔案 | 'appDataFolder' in parents |
| 擁有者為「test@example.org」的檔案 | 'test@example.org' in owners |
| 使用者「test@example.org」具有寫入權限的檔案 | 'test@example.org' in writers |
| 群組「group@example.org」成員具有寫入權限的檔案 | 'group@example.org' in writers |
| 使用者「test@example.org」具有讀取的權限的檔案 | 'test@example.org' in readers |
集合比對運算子 (has) |
|
| 所有應用程式都能看到自訂檔案屬性的檔案 | properties has { key='mass' and value='1.3kg' } |
| 具有自訂檔案屬性的檔案,且該屬性僅供提出要求的應用程式使用 | appProperties has { key='additionalID' and value='8e8aceg2af2ge72e78' } |
| 具有自訂檔案屬性且鍵為「department」的檔案 (不論值為何) | properties has { key='department' } |
邏輯運算子 (and、or、not) |
|
| 名稱包含「hello」和「goodbye」字詞的檔案 | name contains 'hello' and name contains 'goodbye' |
| 名稱不含「hello」一詞的檔案 | not name contains 'hello' |
| 含有「重要」文字且位於垃圾桶中的檔案 | fullText contains 'important' and trashed = true |
| 不含「hello」字詞的檔案 | not fullText contains 'hello' |
| 在特定日期後修改的圖片或影片檔案 | modifiedTime > '2012-06-04T12:00:00' and (mimeType contains 'image/' or mimeType contains 'video/') |
| 與授權使用者共用且名稱含有「hello」的檔案 | sharedWithMe and name contains 'hello' |
| 資料夾或捷徑 | mimeType = 'application/vnd.google-apps.folder' or mimeType = 'application/vnd.google-apps.shortcut' |
| 不在垃圾桶中的「專案計畫」檔案 | name = 'Project Plan' and trashed = false |
| 特定資料夾中不在垃圾桶的直接子項檔案 | '1234567' in parents and trashed = false |
使用用戶端程式庫篩選搜尋結果
下列程式碼範例說明如何使用用戶端程式庫,將搜尋結果篩選為 JPEG 檔案的名稱和 ID。這個範例使用 mimeType 查詢字詞,將結果縮小為 image/jpeg 類型的檔案。同時將 spaces 設為 drive,進一步將搜尋範圍縮小至 Google 雲端硬碟空間。當 nextPageToken 傳回 null 時,表示沒有更多結果。
Java
Python
Node.js
PHP
列出公用資料夾中的檔案
如要搜尋或列出公開共用資料夾中的檔案 (存取權設為「知道連結的任何人」或「網路上公開」),請在 files 資源上使用 list 方法,並將 q 查詢參數設為依 parents 集合中的資料夾 ID 篩選:
'FOLDER_ID' in parents and trashed = false
列出公開資料夾中的檔案時,您可以使用 API 金鑰驗證要求,而不必使用 OAuth 2.0 使用者憑證。如果資料夾位於共用雲端硬碟中,您也必須在要求中設定 supportsAllDrives=true 和 includeItemsFromAllDrives=true。
下列程式碼範例說明如何列出公開資料夾中的檔案:
Node.js
/**
* List files in a public folder using an API key.
* @param {string} folderId The ID of the public folder.
* @param {string} apiKey Your Google Cloud API key.
* @return {Promise<Array>} The list of files.
*/
async function listPublicFolder(folderId, apiKey) {
const {google} = require('googleapis');
const service = google.drive({version: 'v3', auth: apiKey});
try {
const response = await service.files.list({
q: `'${folderId}' in parents and trashed = false`,
fields: 'nextPageToken, files(id, name, mimeType)',
supportsAllDrives: true,
includeItemsFromAllDrives: true,
});
const files = response.data.files;
console.log('Files:');
for (const file of files) {
console.log(`${file.name} (${file.id})`);
}
return files;
} catch (err) {
// TODO(developer): Handle error
console.error(err);
}
}
curl
curl -G \
'https://www.googleapis.com/drive/v3/files' \
--data-urlencode "q='FOLDER_ID' in parents and trashed = false" \
--data-urlencode 'supportsAllDrives=true' \
--data-urlencode 'includeItemsFromAllDrives=true' \
--data-urlencode 'fields=nextPageToken,files(id,name,mimeType)' \
--data-urlencode 'key=API_KEY' \
-H 'Accept: application/json'
更改下列內容:
- FOLDER_ID:公用資料夾的 ID。
- API_KEY:專案的 API 金鑰。
遞迴搜尋子系資料夾和檔案
parents 查詢字詞只會傳回位於指定資料夾中的直接子檔案和資料夾。Drive API 不提供查詢運算子或參數,無法在單一 API 呼叫中遞迴搜尋子資料夾樹狀結構。
如要搜尋資料夾及其所有子資料夾和檔案,應用程式必須執行用戶端樹狀結構遍歷:
- 使用
'FOLDER_ID' in parents and trashed = false查詢目標資料夾的直接子項。 - 篩選
mimeType = 'application/vnd.google-apps.folder'的結果,找出子資料夾。 - 遞迴或疊代查詢每個子資料夾的 ID,以擷取內容。
下列程式碼範例示範如何遞迴搜尋資料夾及其子系:
Node.js
/**
* Recursively searches a folder and all descendant subfolders for files.
* @param {string} folderId The ID of the starting folder.
* @param {Object} authClient An authorized OAuth 2.0 client.
* @return {Promise<Array>} The list of all descendant files.
*/
async function searchFolderRecursively(folderId, authClient) {
const {google} = require('googleapis');
const service = google.drive({version: 'v3', auth: authClient});
const allFiles = [];
const foldersToSearch = [folderId];
try {
while (foldersToSearch.length > 0) {
const currentFolderId = foldersToSearch.pop();
let pageToken = null;
do {
const response = await service.files.list({
q: `'${currentFolderId}' in parents and trashed = false`,
fields: 'nextPageToken, files(id, name, mimeType)',
pageSize: 1000,
supportsAllDrives: true,
includeItemsFromAllDrives: true,
pageToken: pageToken,
});
const files = response.data.files || [];
for (const file of files) {
if (file.mimeType === 'application/vnd.google-apps.folder') {
foldersToSearch.push(file.id);
} else {
allFiles.push(file);
}
}
pageToken = response.data.nextPageToken;
} while (pageToken);
}
return allFiles;
} catch (err) {
// TODO(developer): Handle error
console.error(err);
throw err;
}
}
Python
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
def search_folder_recursively(folder_id, creds):
"""Recursively searches a folder and all descendant subfolders for
files.
Args:
folder_id: The ID of the starting folder.
creds: An authorized OAuth 2.0 credentials object.
Returns:
A list of all descendant file resources.
"""
service = build("drive", "v3", credentials=creds)
all_files = []
folders_to_search = [folder_id]
try:
while folders_to_search:
current_folder_id = folders_to_search.pop()
page_token = None
while True:
response = (
service.files()
.list(
q=f"'{current_folder_id}' in parents and trashed = false",
fields="nextPageToken, files(id, name, mimeType)",
pageSize=1000,
supportsAllDrives=True,
includeItemsFromAllDrives=True,
pageToken=page_token,
)
.execute()
)
for item in response.get("files", []):
if (
item.get("mimeType")
== "application/vnd.google-apps.folder"
):
folders_to_search.append(item.get("id"))
else:
all_files.append(item)
page_token = response.get("nextPageToken")
if not page_token:
break
return all_files
except HttpError as error:
# TODO(developer): Handle error
print(f"An error occurred: {error}")
return None
搜尋具有自訂屬性的檔案
如要搜尋具有自訂檔案屬性的檔案,請使用 properties 或 appProperties 搜尋查詢字詞,並搭配鍵和值。舉例來說,如要搜尋要求應用程式專屬的自訂檔案屬性,且該屬性名為 additionalID,值為 8e8aceg2af2ge72e78:
appProperties has { key='additionalID' and value='8e8aceg2af2ge72e78' }
詳情請參閱「新增自訂檔案屬性」。
依標籤或欄位值搜尋檔案
如要搜尋含有特定標籤的檔案,請使用 labels 搜尋查詢字詞,並指定標籤 ID。
如要搜尋套用特定標籤的檔案,請按照下列步驟操作:
'labels/LABEL_ID' in labels
如要搜尋未套用特定標籤的檔案,請按照下列步驟操作:
not 'labels/LABEL_ID' in labels
如要根據特定標籤欄位值搜尋檔案,請按照下列步驟操作:
labels/LABEL_ID.FIELD_ID = 'VALUE'
如果成功,回應主體會包含與查詢相符的所有檔案例項。詳情請參閱「搜尋具有特定標籤或欄位值的檔案」。
搜尋所有語料庫
使用 list 方法時,user 項目集合預設會設為 corpora 查詢參數。如要搜尋其他項目集合 (例如與 domain 共用的集合),則必須明確設定 corpora 參數。
您可以在單一查詢中搜尋多個語料庫,但如果合併的語料庫過大,API 可能會傳回不完整的結果。查看回應主體中的
incompleteSearch
欄位。如果為 true,則表示省略了部分文件。如要解決這個問題,請縮小 corpora 的範圍,改用 user 或 drive。
在 list 方法上使用 orderBy 查詢參數時,請避免使用 createdTime 鍵查詢大型項目集合,因為這需要額外處理,可能會導致逾時或其他問題。如要對大型商品集合進行時間相關排序,請改用 modifiedTime,因為這項查詢已最佳化,可處理這類查詢。例如,將 orderBy 設為 modifiedTime (或 modifiedTime desc)。
如果省略 orderBy 查詢參數,則沒有預設排列順序,系統會任意傳回項目。