首页 > 解决方案 > 根据 Google 表单答案自动更改目标文件夹的名称

问题描述

我的编码经验很少,但我正在尝试更改此代码段以将目标文件夹的名称更改为我的谷歌表单中的问题响应。该代码按预期工作,并为每个响应的文件上传创建一个文件夹,但文件夹的名称是响应 ID。我在代码中看到它在哪里执行此操作,但我不确定如何将其更改为表单响应中答案的内容。我想更改要创建的文件夹名称,以响应询问用户姓名的问题。

const initialize = () => {
  const form = FormApp.getActiveForm();
  ScriptApp.newTrigger("onFormSubmit").forForm(form).onFormSubmit().create();
};

const onFormSubmit = ({ response } = {}) => {
  try {
    // Get a list of all files uploaded with the response
    const files = response
      .getItemResponses()
      // We are only interested in File Upload type of questions
      .filter(
        (itemResponse) =>
          itemResponse.getItem().getType().toString() === "FILE_UPLOAD"
      )
      .map((itemResponse) => itemResponse.getResponse())
      // The response includes the file ids in an array that we can flatten
      .reduce((a, b) => [...a, ...b], []);

    if (files.length > 0) {
      // Each form response has a unique Id
      const subfolderName = response.getId();
      const parentFolder = DriveApp.getFolderById(PARENT_FOLDER_ID);
      const subfolder = parentFolder.createFolder(subfolderName);
      files.forEach((fileId) => {
        // Move each file into the custom folder
        DriveApp.getFileById(fileId).moveTo(subfolder);
      });
    }
  } catch (f) {
    Logger.log(f);
  }
};

我很抱歉我的经验不足。今年夏天我试图更好地理解 App 脚本,所以作为一个相邻的问题,如果有人有任何资源可以帮助我,那也很棒。

标签: google-apps-scriptgoogle-forms

解决方案


我相信你的目标如下。

  • 您想通过从问题中检索文件夹名称来创建新文件夹,并将上传的文件放入创建的文件夹中。

修改点:

  • 在这种情况下,首先,添加新的问题,用于将文件夹名称输入到 Google 表单。
    • 作为测试,这道题的题目是subfolderName
  • 在您的脚本中,为了检索文件 ID,filter使用mapreduce。在此修改中,为了检索文件 ID 和文件夹名称,我使用reduce. 通过这种方式,我认为可以减少一点工艺成本。

当以上几点反映到您的脚本时,它变成如下。

修改后的脚本:

在测试这个修改后的脚本之前,请再次确认输入文件夹名称作为标题的问题subfolderName

从:

const files = response
  .getItemResponses()
  // We are only interested in File Upload type of questions
  .filter(
    (itemResponse) =>
      itemResponse.getItem().getType().toString() === "FILE_UPLOAD"
  )
  .map((itemResponse) => itemResponse.getResponse())
  // The response includes the file ids in an array that we can flatten
  .reduce((a, b) => [...a, ...b], []);

至:

const {files, subfolderName} = response
  .getItemResponses()
  .reduce((o, e) => {
    const item = e.getItem();
    if (item.getType().toString() === "FILE_UPLOAD") {
      o.files = o.files.concat(e.getResponse());
    } else if (item.getTitle() === "subfolderName") {
      o.subfolderName = e.getResponse();
    }
    return o;
  }, {files: [], subfolderName: ""});
  • 通过上面的修改,filessubfolderName分别是文件ID和文件夹名称。
  • 在此示例中,subfolderName用于在 Google Form 上输入文件夹名称的问题的标题。当您要修改时,请subfolderName根据if (item.getTitle() === "subfolderName")您的实际情况修改。

参考:


推荐阅读