google-apps-scriptgoogle-formsgoogle-forms-api

Google Form Submit Files to Custom File Location is not Moving Uploaded File


I am building a Google Form to upload files. I needed a custom solution so I created a script based of this google setup tutorial and this stackoverflow answer. The first answer in the form response is a name which I would like to use for the file name and the second answer contains the uploaded files. My issue lies in moving the uploaded files to the new folder.

function onFormSubmit(e){
  try{
    const form = FormApp.getActiveForm();
    const folder = DriveApp.getFolderById('FOLDER_ID');
    const responses = form.getResponses()[0];
    const answers = responses.getItemResponses()
    const NAME = answers[0].getResponse();
    const ID = responses.getId();
    const subfolder = folder.createFolder(NAME).setDescription(ID);
    console.log(answers[1].getResponse());
    answers[1].getResponse().forEach(id => DriveApp.getFileById(id).moveTo(subfolder));
  }
  catch(error){console.log(error);}
}

This part is not working:

answers[1].getResponse().forEach(id => DriveApp.getFileById(id).moveTo(subfolder));

Although the id works, the movement of the file(s) to the subfolder that was created is not doing anything. What's the issue? Any code cleanup is also welcome as this is my first time working with this type of code.


Solution

  • In your script, how about the following modification?

    Modified script:

    In this modification, it supposes that your script is the container-bound script of Google Form. And, your function onFormSubmit has already been installed as the OnSubmit trigger. Ref Please be careful about this.

    In this modified script, when the Google Form is submitted, the uploaded file is put into the created subfolder by the script executed with the OnSubmit trigger.

    function onFormSubmit(e) {
      const folder = DriveApp.getFolderById('FOLDER_ID'); // Please set your folder ID.
      const [name, fileIds] = e.response.getItemResponses().map(f => f.getResponse());
      const subfolder = folder.createFolder(name).setDescription(e.response.getId());
      fileIds.forEach(id => DriveApp.getFileById(id).moveTo(subfolder));
    }