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

API Google Drive hỗ trợ một số cách để tì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 đối với 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ả cá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 không cần bất kỳ tham số nào để trả về tất cả các tệp và thư mục.

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

Tìm kiếm các tệp hoặc thư mục cụ thể trong 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 chuỗi truy vấn q bằng 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.

Một chuỗi truy vấn gồm ba phần sau:

query_term operator values

Trong trường hợp:

  • query_term là từ khoá hoặc trường để 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ừ truy vấn và toán tử mà bạn có thể sử dụng tệp và thư mục lọc, hãy xem phần Cụm từ và toán tử truy vấn tìm kiếm.

Ví dụ: chuỗi truy vấn sau đây sẽ lọc kết quả 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 Google Workspace và Google Drive hỗ trợ.

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

Bảng sau đây liệt kê 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 để tìm kiếm.

Bạn cũng phải thoát các ký tự đặc biệt trong tên tệp để đảm bảo truy vấn hoạt động chính xác. Ví dụ: nếu tên tệp chứa cả dấu nháy đơn (') và ký tự dấu gạch chéo ngược ("\"), hãy sử dụng dấu gạch chéo ngược để thoát chúng: name contains 'quinn\'s paper\\essay'.

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ừ "xin chào" not name contains 'hello'
Tệp có chứa văn bản "quan trọng" và nằm trong thùng rác fullText contains 'important' and trashed = true
Tệp có chứa từ "xin chào" 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 thế giớ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'
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 được chia sẻ với người dùng được uỷ quyền có từ "xin chào" trong tên sharedWithMe and name contains 'hello'
Các tệp có thuộc tính tệp tùy chỉnh hiển thị với tất cả ứng dụng properties has { key='mass' and value='1.3kg' }
Tệp có thuộc tính tệp tuỳ chỉnh là riêng tư đối với ứng dụng yêu cầu appProperties has { key='additionalID' and value='8e8aceg2af2ge72e78' }
Các tệp chưa được chia sẻ với bất kỳ ai hoặc miền nào (chỉ riêng tư hoặc được chia sẻ với những người dùng hoặc nhóm cụ thể) visibility = 'limited'

Lọc kết quả tìm kiếm bằng một 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 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ả thành 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 hơn nữa phạm vi tìm kiếm vào dung lượng Drive. Khi nextPageToken trả về null, sẽ 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 kiếm các tệp có thuộc tính tệp tuỳ chỉnh, hãy sử dụng properties hoặc cụm từ tìm kiếm appProperties có khoá và giá trị. Ví dụ: để tìm kiếm 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ị là 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 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 mà nhãn được áp dụng.

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

Bạn cũng có thể tì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 kiếm tập sao lục

Theo mặc định, các lượt tìm kiếm gọi files.list sử dụng corpora của user. Để tìm kiếm 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ù kết quả không đầy đủ có thể được trả về nếu 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ất cả tài liệu không đượ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.