搜尋檔案和資料夾

本指南說明 Google 雲端硬碟 API 支援的幾種檔案和資料夾搜尋方式。

您可以在 files 資源上使用 list 方法,傳回雲端硬碟使用者所有或部分檔案和資料夾。您也可以使用 list 方法,擷取部分資源方法 (例如 get 和 update 方法) 所需的 fileId。

使用 fields 參數

如要指定要在回應中傳回的欄位,可以使用 files 資源的任何方法,設定 fields system 參數。如果省略 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'
名稱為「Project Plan」但不在垃圾桶中的檔案 name = 'Project Plan' and trashed = false
特定資料夾中未移至垃圾桶的檔案 '1234567' in parents and trashed = false

使用用戶端程式庫篩選搜尋結果

下列程式碼範例說明如何使用用戶端程式庫,將搜尋結果篩選為 JPEG 檔案的名稱和 ID。本範例使用 mimeType 查詢字詞,將結果縮小至 image/jpeg 類型的檔案。同時將 spaces 設為 drive,進一步將搜尋範圍縮小至 Google 雲端硬碟空間。nextPageToken 傳回 null 時,表示沒有其他結果。

Java

drive/snippets/drive_v3/src/main/java/SearchFile.java
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.FileList;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/* Class to demonstrate use-case of search files. */
public class SearchFile {

  /**
   * Search for specific set of files.
   *
   * @return search result list.
   * @throws IOException if service account credentials file not found.
   */
  public static List<File> searchFile() throws IOException {
           /*Load pre-authorized user credentials from the environment.
           TODO(developer) - See https://developers.google.com/identity for
           guides on implementing OAuth2 for your application.*/
    GoogleCredentials credentials = GoogleCredentials.getApplicationDefault()
        .createScoped(Arrays.asList(DriveScopes.DRIVE_FILE));
    HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(
        credentials);

    // Build a new authorized API client service.
    Drive service = new Drive.Builder(new NetHttpTransport(),
        GsonFactory.getDefaultInstance(),
        requestInitializer)
        .setApplicationName("Drive samples")
        .build();

    List<File> files = new ArrayList<File>();

    String pageToken = null;
    do {
      FileList result = service.files().list()
          .setQ("mimeType='image/jpeg'")
          .setSpaces("drive")
          .setFields("nextPageToken, files(id, title)")
          .setPageToken(pageToken)
          .execute();
      for (File file : result.getFiles()) {
        System.out.printf("Found file: %s (%s)\n",
            file.getName(), file.getId());
      }

      files.addAll(result.getFiles());

      pageToken = result.getNextPageToken();
    } while (pageToken != null);

    return files;
  }
}

Python

drive/snippets/drive-v3/file_snippet/search_file.py
import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError


def search_file():
  """Search file in drive location

  Load pre-authorized user credentials from the environment.
  TODO(developer) - See https://developers.google.com/identity
  for guides on implementing OAuth2 for the application.
  """
  creds, _ = google.auth.default()

  try:
    # create drive api client
    service = build("drive", "v3", credentials=creds)
    files = []
    page_token = None
    while True:
      # pylint: disable=maybe-no-member
      response = (
          service.files()
          .list(
              q="mimeType='image/jpeg'",
              spaces="drive",
              fields="nextPageToken, files(id, name)",
              pageToken=page_token,
          )
          .execute()
      )
      for file in response.get("files", []):
        # Process change
        print(f'Found file: {file.get("name")}, {file.get("id")}')
      files.extend(response.get("files", []))
      page_token = response.get("nextPageToken", None)
      if page_token is None:
        break

  except HttpError as error:
    print(f"An error occurred: {error}")
    files = None

  return files


if __name__ == "__main__":
  search_file()

Node.js

drive/snippets/drive_v3/file_snippets/search_file.js
import {GoogleAuth} from 'google-auth-library';
import {google} from 'googleapis';

/**
 * Searches for files in Google Drive.
 * @return {Promise<object[]>} A list of files.
 */
async function searchFile() {
  // Authenticate with Google and get an authorized client.
  // TODO (developer): Use an appropriate auth mechanism for your app.
  const auth = new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/drive',
  });

  // Create a new Drive API client (v3).
  const service = google.drive({version: 'v3', auth});

  // Search for files with the specified query.
  const result = await service.files.list({
    q: "mimeType='image/jpeg'",
    fields: 'nextPageToken, files(id, name)',
    spaces: 'drive',
  });

  // Print the name and ID of each found file.
  (result.data.files ?? []).forEach((file) => {
    console.log('Found file:', file.name, file.id);
  });

  return result.data.files ?? [];
}

PHP

drive/snippets/drive_v3/src/DriveSearchFiles.php
<?php
use Google\Client;
use Google\Service\Drive;
function searchFiles()
{
    try {
        $client = new Client();
        $client->useApplicationDefaultCredentials();
        $client->addScope(Drive::DRIVE);
        $driveService = new Drive($client);
        $files = array();
        $pageToken = null;
        do {
            $response = $driveService->files->listFiles(array(
                'q' => "mimeType='image/jpeg'",
                'spaces' => 'drive',
                'pageToken' => $pageToken,
                'fields' => 'nextPageToken, files(id, name)',
            ));
            foreach ($response->files as $file) {
                printf("Found file: %s (%s)\n", $file->name, $file->id);
            }
            array_push($files, $response->files);

            $pageToken = $response->pageToken;
        } while ($pageToken != null);
        return $files;
    } catch(Exception $e) {
       echo "Error Message: ".$e;
    }
}

列出公用資料夾中的檔案

如要搜尋或列出公開共用資料夾中的檔案 (存取權設為「知道連結的任何人」或「網路上公開」),請在 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 金鑰。

搜尋具有自訂屬性的檔案

如要搜尋具有自訂檔案屬性的檔案,請使用 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 查詢參數,系統不會採用預設排序順序,且會任意傳回項目。