You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Google WebApp脚本实现下拉按钮选择后加载对应Drive文件夹图片

直接将现有Code.gs和index.html的全部内容替换为下方对应代码即可实现需求。

Code.gs 完整代码

function doGet(e) {
  var htmlOutput =  HtmlService.createTemplateFromFile('index');
  htmlOutput.pictures = [];
  return htmlOutput.evaluate();
}

function getPictures(folderId) {
    var destination = DriveApp.getFolderById(folderId);
    var files = destination.getFiles();
    var file_array = [];
    
    while (files.hasNext()) {
      var file = files.next();
      if(file.getMimeType().startsWith('image/')){
        file_array.push(file.getId());
      }
    }
    return file_array;
}

function getValuesFromSpreadsheet() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
  return sheet.getRange(1, 1, sheet.getLastRow(), 1).getValues();
}

index.html 完整代码

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
  <div class="dropdown">
     <button onclick="loadpics()" class="dropbtn">选择文件夹</button>
     <div id="myDropdown" class="dropdown-content"></div>
  </div>

  <h1>Display Pictures</h1>
  <table id="picTable">
  <?for(var i = 0; i < pictures.length; i++) { ?>
  <tr><td><img src="https://drive.google.com/uc?export=view&id=<?= pictures[i] ?>" style="width:400px;height:auto;" ></td></tr>
  <? } ?>  
  </table>
  </body>
</html>

<script>
  function loadpics() {
    if(document.getElementById("select1")) return;
    google.script.run.withSuccessHandler(function(ar) {
      let select = document.createElement("select");
      select.id = "select1";
      select.setAttribute("onchange", "selected()");
      document.getElementById("myDropdown").appendChild(select);
      ar.forEach(function(e) {
        let option = document.createElement("option");
        option.value = e[0];
        option.text = e[0];
        document.getElementById("select1").appendChild(option);
      });
    }).getValuesFromSpreadsheet();
  };

  function selected() {
    const folderId = document.getElementById("select1").value;
    google.script.run.withSuccessHandler(function(picIds) {
      const table = document.getElementById("picTable");
      table.innerHTML = '';
      picIds.forEach(id => {
        const tr = document.createElement('tr');
        const td = document.createElement('td');
        const img = document.createElement('img');
        img.src = `https://drive.google.com/uc?export=view&id=${id}`;
        img.style = "width:400px;height:auto;";
        td.appendChild(img);
        tr.appendChild(td);
        table.appendChild(tr);
      })
    }).getPictures(folderId);
  }
</script>

内容的提问来源于stack exchange,提问作者Miyer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 20:27:03