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

คู่มือนี้อธิบายวิธีที่ Google ไดรฟ์ API รองรับการค้นหาไฟล์ และโฟลเดอร์ได้หลายวิธี

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

ใช้พารามิเตอร์ฟิลด์

หากต้องการระบุช่องที่จะแสดงผลในการตอบกลับ คุณสามารถตั้งค่า fields พารามิเตอร์ระบบ ด้วยเมธอดใดก็ได้ของทรัพยากร files หากคุณละเว้นพารามิเตอร์ fields เซิร์ฟเวอร์จะแสดงผลชุดฟิลด์เริ่มต้นที่เฉพาะเจาะจงสำหรับเมธอด เช่น เมธอด list จะแสดงเฉพาะช่อง kind, id, name, mimeType และ resourceKey สำหรับแต่ละไฟล์ หากต้องการแสดงช่องอื่น ให้ดูแสดงช่องที่เฉพาะเจาะจง

รับไฟล์

หากต้องการรับไฟล์ ให้ใช้เมธอด get ในแหล่งข้อมูล files ที่มีพารามิเตอร์เส้นทาง fileId หากไม่ทราบรหัสไฟล์ คุณสามารถแสดงรายการไฟล์ทั้งหมดโดยใช้เมธอด list

เมธอดจะแสดงผลไฟล์เป็นอินสแตนซ์ของทรัพยากร files หากคุณระบุพารามิเตอร์การค้นหา alt=media การตอบกลับจะมีเนื้อหาของไฟล์ในเนื้อหาการตอบกลับ หากต้องการดาวน์โหลดหรือส่งออกไฟล์ โปรดดูดาวน์โหลดและส่งออก ไฟล์

หากต้องการรับทราบความเสี่ยงในการดาวน์โหลดมัลแวร์ที่รู้จักหรือไฟล์อื่นๆ ที่ละเมิด ให้ตั้งค่าพารามิเตอร์การค้นหา acknowledgeAbuse เป็น true ฟิลด์นี้จะใช้ได้ก็ต่อเมื่อมีการตั้งค่าพารามิเตอร์ alt=media และผู้ใช้เป็นเจ้าของไฟล์หรือผู้จัดการไดรฟ์ที่แชร์ซึ่งมีไฟล์อยู่

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

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

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

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

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

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

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'
ไฟล์ที่แก้ไขหลังวันที่ที่กำหนด (เขตเวลาเริ่มต้นคือ UTC) modifiedTime > '2012-06-04T12:00:00'
ไฟล์รูปภาพหรือวิดีโอที่แก้ไขหลังวันที่ที่ระบุ modifiedTime > '2012-06-04T12:00:00' and (mimeType contains 'image/' or mimeType contains 'video/')
ไฟล์ที่ติดดาว starred = true
ไฟล์ภายในคอลเล็กชัน (เช่น รหัสโฟลเดอร์ในคอลเล็กชัน parents) '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 ตัวอย่างนี้ใช้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, files(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
import {GoogleAuth} from 'google-auth-library';
import {google} from 'googleapis';

/**
 * Searches for files in Google Drive.
 * @return {Promise<object[]>} A list of files.
 */
async function searchFile() {
  // Authenticate with Google and get an authorized client.
  // TODO (developer): Use an appropriate auth mechanism for your app.
  const auth = new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/drive',
  });

  // Create a new Drive API client (v3).
  const service = google.drive({version: 'v3', auth});

  // Search for files with the specified query.
  const result = await service.files.list({
    q: "mimeType='image/jpeg'",
    fields: 'nextPageToken, files(id, name)',
    spaces: 'drive',
  });

  // Print the name and ID of each found file.
  (result.data.files ?? []).forEach((file) => {
    console.log('Found file:', file.name, file.id);
  });

  return result.data.files ?? [];
}

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

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

หากต้องการค้นหาไฟล์ที่มีพร็อพเพอร์ตี้ไฟล์ที่กำหนดเอง ให้ใช้คำค้นหา properties หรือ 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'

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

ค้นหาคลังข้อมูล

โดยค่าเริ่มต้น ระบบจะตั้งค่าuserการรวบรวมรายการในพารามิเตอร์การค้นหา corpora เมื่อใช้เมธอด list หากต้องการค้นหาคอลเล็กชันรายการอื่นๆ เช่น คอลเล็กชันที่แชร์กับdomain คุณต้องตั้งค่าพารามิเตอร์ corpora อย่างชัดเจน

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

เมื่อใช้พารามิเตอร์คำค้นหา orderBy ในเมธอด list ให้หลีกเลี่ยงการใช้คีย์ createdTime สำหรับคำค้นหาในคอลเล็กชันรายการขนาดใหญ่ เนื่องจากต้องมีการประมวลผลเพิ่มเติมและอาจทำให้เกิดการหมดเวลาหรือปัญหาอื่นๆ สำหรับการจัดเรียงที่เกี่ยวข้องกับเวลาในคอลเล็กชันรายการขนาดใหญ่ คุณสามารถใช้ modifiedTime แทนได้เนื่องจากได้รับการเพิ่มประสิทธิภาพให้จัดการคำค้นหาเหล่านี้ เช่น ?orderBy=modifiedTime

หากคุณละเว้นพารามิเตอร์การค้นหา orderBy จะไม่มีลำดับการจัดเรียงเริ่มต้นและระบบจะแสดงรายการแบบสุ่ม