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

Sử dụng phương thức files.list để trả về tất cả hoặc chỉ 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 tất cả tệp và thư mục trên trang Drive của tôi của người dùng hiện tại

Sử dụng files.list mà không có bất kỳ tham số nào để trả về tất cả tệp và thư mục.

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

Để tìm kiếm một nhóm 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 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 chứa ba phần sau:

query_term operator values

Trong trường hợp:

  • query_term là cụm từ truy vấn hoặc trường để tìm kiếm. Để xem các cụm từ tìm kiếm có thể dùng để lọc bộ nhớ dùng chung, hãy tham khảo bài viết Toán tử và cụm từ tìm kiếm.

  • operator chỉ định điều kiện cho cụm từ truy vấn. Để xem bạn có thể sử dụng những toán tử nào với mỗi cụm từ truy vấn, hãy tham khảo phần Toán 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.

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:

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

Ví dụ sau cho thấy cách dùng thư viện ứng dụng khách để lọc kết quả tìm kiếm theo tên và mã nhận dạng của các tệp JPEG. Ví dụ này sử dụng cụm từ truy vấn mimeType để thu hẹp kết quả ở các tệp loại image/jpeg. Ví dụ này cũng đặt spaces thành drive để thu hẹp thêm phạm vi 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;
    }
}

Để giới hạn phạm vi tìm kiếm trong các thư mục, hãy sử dụng chuỗi truy vấn để đặt loại MIME thành 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 này hiển thị một số chuỗi truy vấn cơ bản. Mã thực tế còn tuỳ thuộc vào thư viện ứng dụng bạn dùng cho nội dung tìm kiếm của mình.

Nội dung bạn muốn truy vấn Ví dụ:
Tệp có tên "xin chào" name = 'hello'
Các 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'
Các thư mục là các ứng dụng của Google hoặc có loại MIME của 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ó chứa nội dung "quan trọng" và nằm 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 thế giới" fullText contains '"hello world"'
Tệp có truy vấn chứa ký tự "\" (ví dụ: "\authors") fullText contains '\\authors'
Các tệp có mã nhận dạng trong một bộ sưu tập, ví dụ: 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" 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
Tệp được sửa đổi sau một ngày cụ thể modifiedTime > '2012-06-04T12:00:00' // default time zone is UTC
Tệp được chia sẻ với người dùng được uỷ quyền có tên chứa từ "hello" sharedWithMe and name contains 'hello'
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'
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ìm các 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 cụm từ tìm kiếm appProperties kèm theo khoá và giá trị. Ví dụ: để tìm kiếm thuộc tính tệp tuỳ chỉnh có tên là additionalID với giá trị 8e8aceg2af2ge72e78:

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

Để biết thêm thông tin về các thuộc tính tệp tuỳ chỉnh, hãy xem phần 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 với mã nhận dạng nhãn cụ thể. Ví dụ: 'labels/LABEL_ID' in labels

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 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 có lệnh gọi files.list sẽ sử dụng kho dữ liệu 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 miềnGoogle Workspace , hãy sử dụng 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ó thể trả về kết quả không đầy đủ nếu tập sao kết hợp quá lớn. Nếu kết quả incompleteSearchtrue, thì có nghĩa là hệ thống chưa trả về mọi tài liệu.