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

Google表单提交触发含HTML表格及附件邮件的代码报错修复

修复文件上传项的TypeError报错

报错原因

文件上传类型的表单项,itemResponses[i].getResponse()返回的是文件对象数组(支持多文件上传),而非单个文件对象。直接对数组调用.getId()会触发TypeError,因为数组没有这个方法。

修复方案

修改文件上传逻辑,遍历响应返回的文件数组,逐个处理每个文件对象;同时优化HTML表格中的文件上传项显示内容(比如展示文件名)。

修复后的完整代码

function onFormSubmit() {
  var email = "example@gmail.com";
  var subject = "Form Responses";
  var body = "<table>";
  var attachments = [];
  var form = FormApp.getActiveForm();
  var responses = form.getResponses();
  var lastResponse = responses[responses.length-1];
  var itemResponses = lastResponse.getItemResponses();
  
  for (var i = 0; i < itemResponses.length; i++) {
    var question = itemResponses[i].getItem().getTitle();
    var response = itemResponses[i].getResponse();
    var displayResponse = response;
    
    // 处理文件上传项
    if (itemResponses[i].getItem().getType() === FormApp.ItemType.FILE_UPLOAD) {
      var fileNames = [];
      // 遍历文件数组,逐个获取文件Blob和文件名
      for (var j = 0; j < response.length; j++) {
        var file = response[j];
        attachments.push(file.getBlob());
        fileNames.push(file.getName());
      }
      // 表格中显示文件名列表,用逗号分隔
      displayResponse = fileNames.join(', ');
    }
    
    body += "<tr><td><b>" + question + "</b></td><td>" + displayResponse + "</td></tr>";
  }
  body += "</table>";
  GmailApp.sendEmail(email, subject, "", {htmlBody: body, attachments: attachments});
}

关键修改点

  • 对文件上传项的response数组进行遍历,每个元素才是可调用.getBlob()/.getName()的文件对象
  • 将表格中的响应内容替换为文件名列表,避免显示原始数组的字符串形式(比如[File, File])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 23:40:31