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

如何在Gmail Add-on中使用Card Services实现文件上传功能

Gmail Add-on 文件上传实现指南

1. 用Card Services创建文件上传入口

Card Services本身没有原生的文件上传输入组件,你需要通过触发对话框/侧边栏的方式,加载HtmlService构建的上传界面。示例代码如下:

function createAddonCard() {
  // 创建上传按钮
  const uploadButton = CardService.newTextButton()
    .setText("上传文件")
    .setOnClickAction(CardService.newAction()
      .setFunctionName("openUploadDialog") // 触发打开对话框的函数
      .setLoadIndicator(CardService.LoadIndicator.SPINNER));

  // 构建卡片
  const section = CardService.newCardSection()
    .addWidget(uploadButton);

  return CardService.newCardBuilder()
    .addSection(section)
    .build();
}

// 打开上传对话框
function openUploadDialog() {
  const htmlOutput = HtmlService.createHtmlOutputFromFile("uploadDialog")
    .setWidth(400)
    .setHeight(200);
  
  return CardService.newActionResponseBuilder()
    .setDialog(CardService.newDialogAction()
      .setTitle("上传文件")
      .setHtmlOutput(htmlOutput))
    .build();
}

2. 捕获并处理上传文件

接下来创建uploadDialog.html文件,实现前端文件选择和上传逻辑,再通过google.script.run将文件数据传递到后端处理:

uploadDialog.html

<!DOCTYPE html>
<html>
  <body>
    <input type="file" id="fileInput" accept=".pdf,.docx,.txt">
    <button onclick="uploadFile()">开始上传</button>
    <div id="status"></div>

    <script>
      function uploadFile() {
        const fileInput = document.getElementById('fileInput');
        const file = fileInput.files[0];
        if (!file) {
          document.getElementById('status').textContent = "请选择文件";
          return;
        }

        // 显示加载状态
        document.getElementById('status').textContent = "上传中...";

        // 将文件转为Blob,传递给后端函数
        const reader = new FileReader();
        reader.onload = function(e) {
          const blob = Utilities.newBlob(
            e.target.result, 
            file.type, 
            file.name
          );
          
          google.script.run
            .withSuccessHandler(() => {
              document.getElementById('status').textContent = "上传成功!";
              // 可选:关闭对话框
              google.script.host.close();
            })
            .withFailureHandler(error => {
              document.getElementById('status').textContent = `上传失败:${error.message}`;
            })
            .saveUploadedFile(blob);
        };
        reader.readAsArrayBuffer(file);
      }
    </script>
  </body>
</html>

后端处理函数(Apps Script)

function saveUploadedFile(fileBlob) {
  // 示例:保存到Google Drive的根目录
  const folder = DriveApp.getRootFolder();
  folder.createFile(fileBlob);
  
  // 可选:关联到当前邮件(比如添加附件到草稿)
  // const draft = GmailApp.getDraftById(draftId);
  // draft.addAttachment(fileBlob);
}

3. 最佳实践与注意事项

  • 文件限制:Apps Script对Blob大小有配额限制(目前最大50MB),前端要提前校验文件大小,避免上传失败。
  • 格式校验:在前端通过accept属性或JS判断文件类型,减少无效上传。
  • 用户反馈:上传过程中显示加载状态,成功/失败后给出明确提示,提升体验。
  • 权限配置:确保Add-on的清单文件(appsscript.json)中添加了Drive权限,比如:
    "oauthScopes": [
      "https://www.googleapis.com/auth/gmail.addons.execute",
      "https://www.googleapis.com/auth/drive.file"
    ]
    
  • 错误处理:在google.script.run中添加withFailureHandler捕获后端错误,避免静默失败。
  • 避免直接在Card中处理:Card Services的交互能力有限,所有文件上传逻辑必须放在对话框/侧边栏中实现,这是官方推荐的方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 06:16:21