ค้นหาไฟล์และโฟลเดอร์

ใช้เมธอด files.list เพื่อแสดงผลไฟล์และโฟลเดอร์ของผู้ใช้ไดรฟ์ทั้งหมดหรือเพียงบางส่วน

คุณยังใช้เมธอด files.list เพื่อเรียกข้อมูล fileId ที่จำเป็นสำหรับเมธอดทรัพยากรบางอย่าง (เช่น files.get และ files.update) ได้อีกด้วย

ค้นหาไฟล์และโฟลเดอร์ทั้งหมดในไดรฟ์ของฉันของผู้ใช้ปัจจุบัน

ใช้ files.list โดยไม่มีพารามิเตอร์ใดๆ เพื่อแสดงไฟล์และโฟลเดอร์ทั้งหมด

ค้นหาไฟล์หรือโฟลเดอร์ที่ต้องการในไดรฟ์ของฉันของผู้ใช้ปัจจุบัน

หากต้องการค้นหาชุดไฟล์หรือโฟลเดอร์ที่เฉพาะเจาะจง ให้ใช้ช่องสตริงการค้นหา q ที่มี files.list เพื่อกรองไฟล์ที่จะแสดงผลโดยรวมข้อความค้นหาอย่างน้อย 1 รายการเข้าด้วยกัน

สตริงการค้นหาประกอบด้วย 3 ส่วนต่อไปนี้

query_term operator values

โดยที่

  • query_term คือคำหรือช่องในการค้นหา หากต้องการดูคำค้นหาที่ใช้กรองไดรฟ์ที่แชร์ได้ โปรดดูคำค้นหาและโอเปอเรเตอร์ของคำค้นหา

  • operator ระบุเงื่อนไขสำหรับข้อความค้นหา หากต้องการดูว่าโอเปอเรเตอร์ใดใช้ได้กับข้อความค้นหาแต่ละคำ โปรดดูโอเปอเรเตอร์การค้นหา

  • values คือค่าเฉพาะที่คุณต้องการใช้เพื่อกรองผลการค้นหา

ตัวอย่างเช่น สตริงคำค้นหาต่อไปนี้จะกรองการค้นหาให้แสดงเฉพาะโฟลเดอร์

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

ตัวอย่างต่อไปนี้แสดงวิธีใช้ไลบรารีของไคลเอ็นต์เพื่อกรองผลการค้นหาให้เป็นชื่อไฟล์และรหัสของไฟล์ JPEG ตัวอย่างนี้ใช้คำค้นหา mimeType เพื่อจำกัดผลการค้นหาให้แสดงเฉพาะไฟล์ประเภท image/jpeg ตัวอย่างนี้ยังตั้งค่า spaces เป็น drive เพื่อจำกัดการค้นหาให้เหลือเฉพาะ พื้นที่ในไดรฟ์อีกด้วย เมื่อ 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
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;
    }
}

หากต้องการจำกัดการค้นหาเป็นโฟลเดอร์ ให้ใช้สตริงการค้นหาเพื่อตั้งค่าประเภท MIME เป็น q: mimeType = 'application/vnd.google-apps.folder'

ดูข้อมูลเพิ่มเติมเกี่ยวกับประเภท MIME ได้ที่ ประเภท MIME ที่ Google Workspace และ Google ไดรฟ์รองรับ

ตัวอย่างสตริงการค้นหา

ตารางนี้แสดงสตริงการค้นหาพื้นฐานบางส่วน โค้ดจริงจะแตกต่างไปตาม ไลบรารีของไคลเอ็นต์ที่คุณใช้สำหรับการค้นหาของคุณ

สิ่งที่คุณต้องการค้นหา ตัวอย่าง
ไฟล์ที่มีชื่อว่า "สวัสดี" name = 'hello'
ไฟล์ที่มีชื่อที่มีคำว่า "สวัสดี" และ "ลาก่อน" name contains 'hello' and name contains 'goodbye'
ไฟล์ที่มีชื่อที่ไม่มีคำว่า "hello" not name contains 'hello'
โฟลเดอร์ที่เป็นแอป Google หรือมีประเภท MIME เป็นโฟลเดอร์ mimeType = 'application/vnd.google-apps.folder'
ไฟล์ที่ไม่ใช่โฟลเดอร์ mimeType != 'application/vnd.google-apps.folder'
ไฟล์ที่มีข้อความ "สำคัญ" และอยู่ในถังขยะ fullText contains 'important' and trashed = true
ไฟล์ที่มีคำว่า "สวัสดี" fullText contains 'hello'
ไฟล์ที่ไม่มีคำว่า "สวัสดี" not fullText contains 'hello'
ไฟล์ที่มีวลี "hello world" ทุกประการ fullText contains '"hello world"'
ไฟล์ที่มีคำค้นหาที่มีอักขระ "\" (เช่น "\authors") fullText contains '\\authors'
ไฟล์ที่มีรหัสภายในคอลเล็กชัน เช่น คอลเล็กชัน parents '1234567' in parents
ไฟล์ในโฟลเดอร์ข้อมูลแอปพลิเคชันในคอลเล็กชัน 'appDataFolder' in parents
ไฟล์ที่ผู้ใช้ "test@example.org" มีสิทธิ์เขียน 'test@example.org' in writers
ไฟล์ที่สมาชิกของกลุ่ม "group@example.org" มีสิทธิ์เขียน 'group@example.org' in writers
ไฟล์ที่แก้ไขหลังวันที่ที่ระบุ modifiedTime > '2012-06-04T12:00:00' // default time zone is UTC
ไฟล์ที่แชร์กับผู้ใช้ที่ได้รับอนุญาตโดยมีคำว่า "hello" ในชื่อ sharedWithMe and name contains 'hello'
ไฟล์ที่ไม่ได้แชร์กับใครหรือโดเมนเลย (เฉพาะแบบส่วนตัว หรือแชร์กับผู้ใช้หรือกลุ่มที่ระบุ) visibility = 'limited'
ไฟล์รูปภาพหรือวิดีโอที่แก้ไขหลังวันที่ที่ระบุ modifiedTime > '2012-06-04T12:00:00' and (mimeType contains 'image/' or mimeType contains 'video/')

ค้นหาไฟล์ด้วยพร็อพเพอร์ตี้ไฟล์ที่กำหนดเอง

หากต้องการค้นหาไฟล์ด้วยพร็อพเพอร์ตี้ไฟล์ที่กำหนดเอง ให้ใช้ข้อความค้นหา appProperties กับคีย์และค่า เช่น หากต้องการค้นหาพร็อพเพอร์ตี้ไฟล์ที่กำหนดเองซึ่งชื่อ additionalID ที่มีค่าเป็น 8e8aceg2af2ge72e78 ให้ทำดังนี้

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

ดูข้อมูลเพิ่มเติมเกี่ยวกับพร็อพเพอร์ตี้ไฟล์ที่กําหนดเองได้ที่เพิ่มพร็อพเพอร์ตี้ไฟล์ที่กําหนดเอง

ค้นหาไฟล์ที่มีป้ายกำกับหรือค่าในช่องที่เจาะจง

หากต้องการค้นหาไฟล์ที่มีป้ายกำกับเฉพาะ ให้ใช้คำค้นหา labels ที่มีรหัสป้ายกำกับเฉพาะ ตัวอย่าง: 'labels/LABEL_ID' in labels

หากต้องการค้นหาไฟล์โดยไม่มีรหัสป้ายกำกับที่เฉพาะเจาะจง ให้ทำดังนี้ Not 'labels/LABEL_ID' in labels

นอกจากนี้ ยังสามารถค้นหาไฟล์ตามค่าในช่องข้อมูลที่ต้องการได้อีกด้วย เช่น หากต้องการค้นหาไฟล์ที่มีค่าข้อความ ให้ใช้รูปแบบต่อไปนี้ labels/LABEL_ID.text_field_id = 'TEXT'

ดูข้อมูลเพิ่มเติมได้ที่ค้นหาไฟล์ที่มีป้ายกำกับหรือค่าในช่องที่เจาะจง

ค้นหาคลัง

การค้นหาที่เรียก files.list จะใช้คลังข้อมูล user โดยค่าเริ่มต้น หากต้องการค้นหาคลังอื่นๆ เช่น ไฟล์ที่แชร์กับโดเมนGoogle Workspace ให้ใช้พารามิเตอร์ corpora

อาจมีการค้นหาคลังข้อมูลหลายรายการในคำค้นหาเดียว แต่อาจแสดงผลที่ไม่สมบูรณ์หากคลังข้อมูลแบบรวมมีขนาดใหญ่เกินไป หากผลลัพธ์ incompleteSearch คือ true แสดงว่าระบบไม่ได้ส่งคืนเอกสารทั้งหมด