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

使用Google Apps Script向Google Sheets单元格传图遇提交无响应求助

问题排查与修复方案

核心问题分析

  • HTML转义字符错误:代码中大量使用"替代双引号,导致HTML结构和JS逻辑解析异常,表单元素属性、JS事件绑定均受影响。
  • 表单数据传递方式错误:直接将form对象传给google.script.run.upload(),无法正确提取文件Blob,这是界面无响应的关键原因。
  • 类型转换缺失:position参数为字符串类型,传给getRange()时需转为数字,否则会引发范围获取错误。
  • 错误处理缺失:未添加失败回调,无法捕获上传过程中的错误,导致界面卡住且无任何提示。

修复后的完整代码

Code.gs

function addImage() { 
  var filename = 'Row';
  var htmlTemp = HtmlService.createTemplateFromFile('Index');
  htmlTemp.fName = filename;
  htmlTemp.position = 2;
  var html = htmlTemp.evaluate().setHeight(96).setWidth(415);
  SpreadsheetApp.getUi().showModalDialog(html, 'Upload');
}

function upload(obj) {
  // 转换行号为数字类型
  var rowNum = Number(obj.position);
  if (isNaN(rowNum)) throw new Error("无效的行号");

  var newFileName = obj.fname;
  var blob = obj.file;

  // 替换为你的Drive文件夹ID
  var upFile = DriveApp.getFolderById("你的文件夹ID").createFile(blob).setName(newFileName);
  var fileUrl = upFile.getUrl();

  var urlCell = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1').getRange(rowNum, 5);
  // 直接构造HYPERLINK公式,无需转义双引号
  urlCell.setValue(`=HYPERLINK("${fileUrl}", "View image")`);
  
  return "上传成功";
}

Index.html

<!DOCTYPE html>
<html>
  <head>
    <base target="_center">
    <link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
    <script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
  </head>
  <body>
    <form id="myForm">
      Please upload image below.<br /><br />
      <input type="hidden" name="fname" id="fname" value="<?= fName ?>"/>
      <input type="hidden" name="position" id="position" value="<?= position ?>"/>
      <input type="file" name="file" id="file" accept="image/jpeg,.pdf" />
      <input type="button" value="Submit" class="action" onclick="formData(this.parentNode)" />
      <input type="button" value="Close" onclick="google.script.host.close()" />
    </form>
    <script>
      // 禁用表单默认提交行为
      window.onload = function() {
        document.getElementById('myForm').addEventListener('submit', function(event) {
          event.preventDefault();
        });  
      }

      function formData(formObj){
        // 手动构建FormData对象,确保文件Blob能正确传递
        var formData = new FormData(formObj);
        var uploadData = {
          fname: formData.get('fname'),
          position: formData.get('position'),
          file: formData.get('file')
        };

        // 添加成功和失败回调
        google.script.run
          .withSuccessHandler(closeIt)
          .withFailureHandler(handleError)
          .upload(uploadData);
      }   

      function closeIt(message){
        console.log(message);
        google.script.host.close();
      };   

      function handleError(error){
        alert("上传失败:" + error.message);
        console.error(error);
      }
    </script>
  </body>
</html>

关键修复点说明

  • 替换HTML转义字符:将所有&quot;改为标准双引号,确保HTML和JS代码正常解析。
  • 正确传递文件数据:使用FormData手动提取表单数据,确保文件Blob能被google.script.run正确序列化传递到服务端。
  • 类型转换:将position字符串转为数字,避免getRange()参数类型错误。
  • 添加错误处理:新增withFailureHandler捕获上传错误,弹出提示并打印日志,方便排查问题。
  • 简化HYPERLINK公式:使用模板字符串直接构造公式,无需手动转义双引号,代码更简洁。

测试步骤

  1. 替换Code.gs中的你的文件夹ID为实际Google Drive文件夹ID。
  2. 保存所有代码后,重新运行addImage()函数。
  3. 选择JPEG图片点击Submit,此时应能正常上传并关闭对话框,Sheet1的第2行第5列会生成图片链接。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 23:21:06