google-apps-script - 根据 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 表单。
- 作为测试,这道题的题目是
subfolderName
。
- 作为测试,这道题的题目是
- 在您的脚本中,为了检索文件 ID,
filter
使用map
和reduce
。在此修改中,为了检索文件 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: ""});
- 通过上面的修改,
files
和subfolderName
分别是文件ID和文件夹名称。 - 在此示例中,
subfolderName
用于在 Google Form 上输入文件夹名称的问题的标题。当您要修改时,请subfolderName
根据if (item.getTitle() === "subfolderName")
您的实际情况修改。
参考:
推荐阅读
- java - 一段时间后无限亚军滞后
- rust - 如何在结构中写入 KdTree 成员的类型?
- flutter - 使用颤振关闭应用程序时,是否可以运行类似“后台服务”的代码?
- regex - Regex if then without else in ripgrep
- azure-logic-apps - 如何检查Outlook文件夹是否有邮件
- r - boxr 包中的 box_dir_create() 函数未在 Box 中创建文件夹
- c# - 在 ViewModel 中将值从一个模型传递到另一个模型
- javascript - 如何将数据从 get 函数获取到 node.js 中同一个 js 文件中的另一个函数?
- ios - 哪个使用更少的内存?一个带有 5 个按钮的视图控制器,还是一个带有 5 个项目的表格视图的视图控制器?
- c# - 如何在c#中查找excel工作表每一列的行数?