Google Apps Script ค้นหาไฟล์/โฟลเดอร์ ใน Google Drive

 

✅ การทำงาน

  • เมื่อพิมพ์ในช่องค้นหา (onkeyup) จะเรียก searchDrive() ที่ฝั่งเซิร์ฟเวอร์ (GAS)
  • ค้นหาทั้ง ไฟล์ และโฟลเดอร์ ที่มีชื่อประกอบด้วยข้อความที่พิมพ์
  • แสดงผลเป็นลิสต์ พร้อมลิงก์เปิดในแท็บใหม่


code.gs

     
function searchDrive(query) {
  let results = [];
  if (!query) return results;

  // ระบุไอดีโฟลเดอร์หลัก
  const parentId = "xxxxxxxx";     // ไอดีของโฟลเดอร์หลัก
  const parentFolder = DriveApp.getFolderById(parentId);

  // --- ค้นหาเฉพาะโฟลเดอร์ย่อยในโฟลเดอร์หลัก ---
  const subFolders = parentFolder.getFolders();
  while (subFolders.hasNext()) {
    const folder = subFolders.next();
    if (folder.getName().toLowerCase().includes(query.toLowerCase())) {
      results.push({
        name: folder.getName(),
        url: folder.getUrl(),
        type: "โฟลเดอร์"
      });
    }
  }

  // (ค้นไฟล์ในโฟลเดอร์)
  
  const files = parentFolder.getFiles();
  while (files.hasNext()) {
    const file = files.next();
    if (file.getName().toLowerCase().includes(query.toLowerCase())) {
      results.push({
        name: file.getName(),
        url: file.getUrl(),
        type: "ไฟล์"
      });
    }
  }
  

  return results;
}




    


index.html

     
<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/js/bootstrap.bundle.min.js"></script>
    <script>
      function search() {
        const query = document.getElementById("searchBox").value;
        if (!query) {
          document.getElementById("results").innerHTML = "พิมพ์คำค้นหาก่อน";
          return;
        }

        google.script.run.withSuccessHandler(showResults).searchDrive(query);
      }

      function showResults(data) {
        let html = "";
        if (data.length === 0) {
          html = "<p>ไม่พบผลลัพธ์</p>";
        } else {
          html = "<ul>";
          data.forEach(item => {
            html += `<li>[${item.type}] <a href="${item.url}" target="_blank">${item.name}</a></li>`;
          });
          html += "</ul>";
        }
        document.getElementById("results").innerHTML = html;
      }
    </script>
  </head>
  <body>
    <div class="container">
       <h3 class="mt-5  text-center">🔍 ค้นหาไฟล์/โฟลเดอร์ ใน Google Drive</h3>
      <div class="row justify-content-center">
        <div class="col-md-6 ">
          <input class="form-control mt-3" type="text" id="searchBox" onkeyup="search()" placeholder="พิมพ์คำค้นหา...">
        </div>
      </div>
      <div class="container" id="results"></div>
    </div>
  </body>
</html>



    






แสดงความคิดเห็น (0)
ใหม่กว่า เก่ากว่า