搜尋檔案和資料夾

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

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

使用 fields 參數

如要指定要在回應中傳回的欄位,可以使用 files 資源的任何方法,設定 fields system 參數。如果省略 fields 參數,伺服器會傳回方法專屬的預設欄位集。舉例來說,list 方法只會傳回每個檔案的 kindidnamemimeTyperesourceKey 欄位。如要傳回不同欄位,請參閱「傳回特定欄位」。

取得檔案

如要取得檔案,請在 files 資源上使用 get 方法,並提供 fileId 路徑參數。如果您不知道檔案 ID,可以使用 list 方法列出所有檔案

這個方法會以 files 資源的執行個體形式傳回檔案。如果您提供 alt=media 查詢參數,回應主體就會包含檔案內容。如要下載或匯出檔案,請參閱「下載及匯出檔案」。

如要確認下載已知惡意軟體或其他濫用檔案的風險,請將 acknowledgeAbuse 查詢參數設為 true。只有在設定 alt=media 參數,且使用者是檔案擁有者,或檔案所在共用雲端硬碟的召集人時,這個欄位才適用。

搜尋目前使用者「我的雲端硬碟」中的所有檔案和資料夾

使用不含任何參數的 list 方法,即可傳回所有檔案和資料夾。

GET https://www.googleapis.com/drive/v3/files

搜尋目前使用者「我的雲端硬碟」中的特定檔案或資料夾

如要搜尋特定檔案或資料夾,請使用 q 欄位中的查詢字串,並搭配 list 方法來篩選檔案,藉此傳回一或多個搜尋字詞的組合。

查詢字串語法包含下列三部分:

query_term operator values

在此情況下:

  • query_term 是要搜尋的查詢字詞或欄位。

  • operator 指定查詢字詞的條件。

  • values 是要用來篩選搜尋結果的特定值。

舉例來說,下列查詢字串會設定 MIME 類型,將搜尋結果篩選為僅傳回資料夾:

q: mimeType = 'application/vnd.google-apps.folder'

如要查看所有檔案查詢字詞,請參閱檔案專屬查詢字詞

如要查看可用於建構查詢的所有查詢運算子,請參閱「查詢運算子」。

查詢字串範例

下表列出一些基本查詢字串的範例。實際程式碼會因您用於搜尋的用戶端程式庫而異。

此外,您也必須逸出檔案名稱中的特殊字元,確保查詢作業正常運作。舉例來說,如果檔案名稱同時包含單引號 (') 和反斜線 ("\") 字元,請使用反斜線逸出這些字元:name contains 'quinn\'s paper\\essay'

要查詢的內容 範例
名稱為「hello」的檔案 name = 'hello'
名稱包含「hello」和「goodbye」的檔案 name contains 'hello' and name contains 'goodbye'
名稱不含「hello」一詞的檔案 not name contains 'hello'
垃圾桶中含有「重要」一詞的檔案 fullText contains 'important' and trashed = true
含有「hello」字詞的檔案 fullText contains 'hello'
不含「hello」字詞的檔案 not fullText contains 'hello'
含有「hello world」這個確切詞組的檔案 fullText contains '"hello world"'
查詢含有「\」字元 (例如「\authors」) 的檔案 fullText contains '\\authors'
資料夾 mimeType = 'application/vnd.google-apps.folder'
非資料夾的檔案 mimeType != 'application/vnd.google-apps.folder'
在指定日期後修改的檔案 (預設時區為世界標準時間) modifiedTime > '2012-06-04T12:00:00'
在特定日期後修改的圖片或影片檔案 modifiedTime > '2012-06-04T12:00:00' and (mimeType contains 'image/' or mimeType contains 'video/')
已加星號的檔案 starred = true
集合中的檔案 (例如 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
名稱含有「hello」且與授權使用者共用的檔案 sharedWithMe and name contains 'hello'
所有應用程式都能看到具有自訂檔案屬性的檔案 properties has { key='mass' and value='1.3kg' }
具有自訂檔案屬性的檔案,且該屬性僅供要求存取的應用程式使用 appProperties has { key='additionalID' and value='8e8aceg2af2ge72e78' }
未與任何人或網域共用的檔案 (僅限私人檔案,或與特定使用者或群組共用的檔案) visibility = 'limited'

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

下列程式碼範例說明如何使用用戶端程式庫,將搜尋結果篩選為 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, items(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
/**
 * Search file in drive location
 * @return{obj} data file
 * */
async function searchFile() {
  const {GoogleAuth} = require('google-auth-library');
  const {google} = require('googleapis');

  // Get credentials and build service
  // TODO (developer) - Use appropriate auth mechanism for your app
  const auth = new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/drive',
  });
  const service = google.drive({version: 'v3', auth});
  const files = [];
  try {
    const res = await service.files.list({
      q: 'mimeType=\'image/jpeg\'',
      fields: 'nextPageToken, files(id, name)',
      spaces: 'drive',
    });
    Array.prototype.push.apply(files, res.files);
    res.data.files.forEach(function(file) {
      console.log('Found file:', file.name, file.id);
    });
    return res.data.files;
  } catch (err) {
    // TODO(developer) - Handle error
    throw err;
  }
}

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;
    }
}

搜尋具有自訂檔案屬性的檔案

如要搜尋具有自訂檔案屬性的檔案,請使用 propertiesappProperties 搜尋查詢字詞,並提供鍵和值。舉例來說,如要搜尋名為「additionalID」的應用程式專屬自訂檔案屬性,且值為「8e8aceg2af2ge72e78」,請使用下列程式碼:

appProperties has { key='additionalID' and value='8e8aceg2af2ge72e78' }

詳情請參閱「新增自訂檔案屬性」。

搜尋含有特定標籤或欄位值的檔案

如要搜尋具有特定標籤的檔案,請使用 labels 搜尋查詢字詞和特定標籤 ID。例如:'labels/LABEL_ID' in labels。如果成功,回應主體會包含套用標籤的所有檔案例項。

如要搜尋沒有特定標籤 ID 的檔案,請輸入 Not 'labels/LABEL_ID' in labels

您也可以根據特定欄位值搜尋檔案。舉例來說,如要搜尋具有文字值的檔案,請使用 labels/LABEL_ID.text_field_id ='TEXT'

詳情請參閱依特定標籤或欄位值搜尋檔案

搜尋語料庫

呼叫 list 方法的搜尋會預設使用 usercorpora。如要搜尋其他語料庫 (例如與 domain 共用的檔案),請設定 corpora 參數。

單一查詢可搜尋多個語料庫,但如果合併的語料庫過大,可能會傳回不完整的結果。如果回應主體中包含 incompleteSearch,表示並非所有文件都已傳回。true如果發生這種情況,請選擇其他語料庫 (例如 userdrive) 縮小查詢範圍。