Tìm tệp và thư mục

API Google Drive hỗ trợ một số cách để tìm kiếm tệp và thư mục.

Bạn có thể sử dụng phương thức files.list để trả về tất cả hoặc một số tệp và thư mục của người dùng Drive. Bạn cũng có thể sử dụng phương thức files.list để truy xuất fileId cần thiết cho một số phương thức tài nguyên (chẳng hạn như files.getfiles.update).

Tìm kiếm tất cả tệp và thư mục trên phần Drive của tôi của người dùng hiện tại

Sử dụng phương thức files.list mà không có tham số để trả về tất cả tệp và thư mục.

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

Tìm các tệp hoặc thư mục cụ thể trên phần Drive của tôi của người dùng hiện tại

Để tìm kiếm một tập hợp tệp hoặc thư mục cụ thể, hãy sử dụng trường q của chuỗi truy vấn với phương thức files.list để lọc các tệp cần trả về bằng cách kết hợp một hoặc nhiều cụm từ tìm kiếm.

Chuỗi truy vấn chứa ba phần sau:

query_term operator values

Trong trường hợp:

  • query_term là trường hoặc cụm từ truy vấn để tìm kiếm.

  • operator chỉ định điều kiện cho cụm từ truy vấn.

  • values là các giá trị cụ thể mà bạn muốn dùng để lọc kết quả tìm kiếm.

Để xem các cụm từ tìm kiếm và toán tử mà bạn có thể dùng các tệp và thư mục bộ lọc, hãy xem phần Toán tử và cụm từ truy vấn tìm kiếm.

Ví dụ: chuỗi truy vấn sau đây lọc nội dung tìm kiếm để chỉ trả về các thư mục bằng cách đặt loại MIME:

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

Để biết thêm thông tin về các loại MIME, hãy xem bài viết Các loại MIME được hỗ trợ trên Google Workspace và Google Drive.

Ví dụ về chuỗi truy vấn

Bảng sau đây liệt kê các ví dụ về một số chuỗi truy vấn cơ bản. Mã thực tế sẽ khác nhau tuỳ thuộc vào thư viện ứng dụng mà bạn dùng cho nội dung tìm kiếm.

Nội dung bạn muốn truy vấn Ví dụ:
Tệp có tên "xin chào" name = 'hello'
Tệp có tên chứa từ "xin chào" và "tạm biệt" name contains 'hello' and name contains 'goodbye'
Tệp có tên không chứa từ "hello" not name contains 'hello'
Tệp có chứa nội dung "quan trọng" và trong thùng rác fullText contains 'important' and trashed = true
Tệp có chứa từ "hello" fullText contains 'hello'
Tệp không có từ "xin chào" not fullText contains 'hello'
Tệp có chứa chính xác cụm từ "xin chào mọi người" fullText contains '"hello world"'
Tệp có truy vấn chứa ký tự "\" (ví dụ: "\authors") fullText contains '\\authors'
Tệp là thư mục mimeType = 'application/vnd.google-apps.folder'
Các tệp không phải là thư mục mimeType != 'application/vnd.google-apps.folder'
Tệp được sửa đổi sau một ngày cụ thể (múi giờ mặc định là UTC) modifiedTime > '2012-06-04T12:00:00'
Tệp hình ảnh hoặc video được sửa đổi sau một ngày cụ thể modifiedTime > '2012-06-04T12:00:00' and (mimeType contains 'image/' or mimeType contains 'video/')
Tệp được gắn dấu sao starred = true
Các tệp trong một bộ sưu tập (ví dụ: mã thư mục trong bộ sưu tập parents) '1234567' in parents
Các tệp trong thư mục dữ liệu ứng dụng trong một bộ sưu tập 'appDataFolder' in parents
Các tệp mà người dùng "test@example.org" là chủ sở hữu 'test@example.org' in owners
Các tệp mà người dùng "test@example.org" có quyền ghi 'test@example.org' in writers
Các tệp mà thành viên của nhóm "group@example.org" có quyền ghi 'group@example.org' in writers
Các tệp đã chia sẻ với người dùng được uỷ quyền có tên chứa từ "xin chào" sharedWithMe and name contains 'hello'
Tệp có thuộc tính tệp tuỳ chỉnh hiển thị cho tất cả ứng dụng properties has { key='mass' and value='1.3kg' }
Các tệp có thuộc tính tệp tuỳ chỉnh chỉ dành riêng cho ứng dụng yêu cầu appProperties has { key='additionalID' and value='8e8aceg2af2ge72e78' }
Tệp chưa được chia sẻ với bất kỳ ai hoặc miền (chỉ riêng tư hoặc được chia sẻ với người dùng hoặc nhóm cụ thể) visibility = 'limited'

Lọc kết quả tìm kiếm bằng thư viện ứng dụng

Mã mẫu sau đây cho biết cách sử dụng thư viện ứng dụng để lọc kết quả tìm kiếm theo tên tệp và mã nhận dạng của tệp JPEG. Mẫu này sử dụng cụm từ truy vấn mimeType để thu hẹp kết quả ở các tệp thuộc loại image/jpeg. Thao tác này cũng đặt spaces thành drive để thu hẹp thêm nội dung tìm kiếm trong không gian Drive. Khi nextPageToken trả về null, không có kết quả nào khác.

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

1.199

drive/snippets/drive_v3/src/DriveSearchFiles.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;
    }
}

Tìm tệp có thuộc tính tệp tuỳ chỉnh

Để tìm các tệp có thuộc tính tệp tuỳ chỉnh, hãy sử dụng cụm từ tìm kiếm properties hoặc appProperties kèm theo khoá và giá trị. Ví dụ: để tìm kiếm một thuộc tính tệp tuỳ chỉnh dành riêng cho ứng dụng yêu cầu có tên là additionalID với giá trị 8e8aceg2af2ge72e78:

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

Để biết thêm thông tin, hãy xem bài viết Thêm thuộc tính tệp tuỳ chỉnh.

Tìm tệp có nhãn hoặc giá trị trường cụ thể

Để tìm kiếm các tệp có nhãn cụ thể, hãy sử dụng cụm từ tìm kiếm labels có mã nhận dạng nhãn cụ thể. Ví dụ: 'labels/LABEL_ID' in labels. Nếu thành công, nội dung phản hồi sẽ chứa mọi thực thể tệp có áp dụng nhãn.

Cách tìm kiếm các tệp không có mã nhãn cụ thể: Not 'labels/LABEL_ID' in labels.

Bạn cũng có thể tìm kiếm tệp dựa trên các giá trị cụ thể của trường. Ví dụ: để tìm kiếm các tệp có giá trị văn bản: labels/LABEL_ID.text_field_id ='TEXT'.

Để biết thêm thông tin, hãy xem phần Tìm kiếm tệp có nhãn hoặc giá trị trường cụ thể.

Tìm tập sao lục

Theo mặc định, các nội dung tìm kiếm gọi files.list sử dụng corpora của user. Để tìm kiếm các tập sao lục khác, chẳng hạn như các tệp được chia sẻ với domain, hãy đặt tham số corpora.

Có thể tìm kiếm nhiều tập sao lục trong một truy vấn, mặc dù các tập sao lục không hoàn chỉnh có thể được trả về nếu các tập sao lục kết hợp quá lớn. Nếu incompleteSearchtrue trong nội dung phản hồi, thì tức là tất cả tài liệu chưa được trả về. Nếu điều này xảy ra, bạn nên thu hẹp truy vấn của mình bằng cách chọn một tập sao lục khác, chẳng hạn như user hoặc drive.