Search code examples
javascriptgoogle-apps-scriptgoogle-sheetsgoogle-formsdrive

Upload files to Google Drive from Google forms file uploads renamed with field name (string value) collected from the Form Response?


This code currently takes the unique ID from the form response and puts it as the folder name where all the uploaded file goes to. I want to change the code so that it takes a text field from the Google Form response for organized view, such as First Name_Last Name.

const PARENT_FOLDER_ID = "2ih2384723847234878h23jkbi2j3b4ijb23i4bhwed34f";

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);
  }
};

Solution

  • Let's say the names are the first and second questions.

    /* ... */
    
    const n = response.getItemResponses().slice(0, 2)
    const fn = n[0].getResponse();
    const ln = n[1].getResponse();
    
    /* ... */
    
    const subfolderName = `${fn}_${ln}`;
    
    /* ... */