I have a Google Form which requires files to be uploaded. I have added a script which creates a sub-folder from a Form field (in this case a student number).
In this image some of the auto-generated sub-folders are visible, as well as the custom sub-folder (in this case for a student number 999999999
For the initial part of the form 4 files have to be uploaded. Once the form is submitted, there are now three copies of the files; one set in the root "My Drive", one set in the auto-generated Google Drive sub-folders, one set in the custom sub-folder (student number).
I used code I found on Stackoverflow and made minor modifications (Google Drive custom sub-folder address & Form Field to be used to create the custom sub-folder - How to Move File Uploads from Google Forms to a Specific Folder & Subfolders in Google Drive)
Here is my code:
const PARENT_FOLDER_ID = "1x_SpJWrQ3FLuosjooPD3mNMVKphvQZMAf59Hd6O0HYwlguaxCzWaqRR3rxBkWI9P26zKx1CF";
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 StudentNumber = response.getItemResponses()[2].getResponse() // text in third answer
const subfolderName = StudentNumber
// 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.createFolder(subfolderName);
files.forEach((fileId) => {
// Move each file into the custom folder
DriveApp.getFileById(fileId).moveTo(subfolder);
});
}
} catch (f) {
Logger.log(f);
}
};
How do I prevent/delete multiple copies of the same files when submitting a Form response? I only want files in the custom sub-folder.