I have a google form that collects details of a set of individuals. They select several options and finally upload a file. I want these files to be uploaded to a specific folder (based on form selection options) that is already created in the google drive. I have found a very good answer in the forum, however, the search of the subfolder (not there is the below reference) is a bit cloudy to me.
Reference: How to Move File Uploads from Google Forms to a Specific Folder & Subfolders in Google Drive
Example: A person fills the form Q1. "1", Q2. "form 1" <- the upload. My other options for Q1 are 2 and 3. Inside my custom "reports" folder (in goolge drive) I have placed the 1,2 and 3 folders. I want this particular upload to end up in the "1" folder. With the below code, the file gets uploaded to some other folder, i.e., Form uploads.
const PARENT_FOLDER_ID = "<folder ID>";
const initialize = () => {
const form = FormApp.getActiveForm();
ScriptApp.newTrigger("onFormSubmit").forForm(form).onFormSubmit().create();
};
const onFormSubmit = ({ response } = {}) => {
try {
// Get some useful data to create the subfolder name
const answer = response.getItemResponses()[0].getResponse() // text in first answer
// 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 parentFolder = DriveApp.getFolderById(PARENT_FOLDER_ID);
const subfolder = parentFolder.getFoldersByName(answer).next(); //I am stuck at this point, how can I search for the particular folder and push the file inside
files.forEach((fileId) => {
// Move each file into the custom folder
DriveApp.getFileById(fileId).moveTo(subfolder);
});
}
} catch (f) {
Logger.log(f);
}
};