Home > Back-end >  Upload google form files to two different google drive folders
Upload google form files to two different google drive folders

Time:11-24

I have a google form that has two file upload sections. I want to be able to upload those files to two different folders. The files in the first file upload section should go in Folder one and the files in the second file upload section should go in folder two. I also want to automatically name the folders based on the name of the senders. Folders should go as follow: sendername_1, sendername_2, etc, if the senders have the same name. How would I make this happen? I found the script below but it seems to only work with folder 1. Folder 2 has the files from the second file upload section but it doesn't automatically create a folder for them.

    function onFormSubmit(e) {
  

    const folderId = "1y40PNXYXSm7Ue_b6nbVnauz7dzKiKj4u";  // Please set top folder ID of the destination folders.

  const form = FormApp.getActiveForm();
  const formResponses = form.getResponses();
  const itemResponses = formResponses[formResponses.length-1].getItemResponses();

  Utilities.sleep(3000); // This line might not be required.

  // Prepare the folder.
  const destFolder = DriveApp.getFolderById(folderId);
  const folderName = itemResponses[0].getResponse();
  const subFolder = destFolder.getFoldersByName(folderName);
  const folder = subFolder.hasNext() ? subFolder : destFolder.createFolder(folderName);

  // Move files to the folder.
itemResponses[2].getResponse().forEach(id => DriveApp.getFileById(id).moveTo(folder));

}

CodePudding user response:

Here is a sample of how I would approach it:

function getIdFromUrl(url) 
{ 
  return url.match(/[-\w]{25,}/); 
}

function automateFile (e) {

var name = e.values[2]
var file1 = e.values[3]; 
var file2 = e.values[4];
var drive = DriveApp;
var parentFolder = drive.getFolderById("1vJcsklbZ_Lk0b3CH0JxUHN8UzNI0eKXV"); //Set Parent Folder ID
var createFolder1 = drive.createFolder(name   '_1').moveTo(parentFolder);
var createFolder2 = drive.createFolder(name   '_2').moveTo(parentFolder);

var getfileId1 = getIdFromUrl(file1); //Gets the file ID 1
  drive.getFileById(getfileId1).moveTo(createFolder1); // Moves the file to Folder1 

var getfileId2 = getIdFromUrl(file2); //Gets the file ID 2
  drive.getFileById(getfileId2).moveTo(createFolder2); // Moves the file to Folder2 

}

NOTES: This script was done on Google Sheets Apps Script, which is the created sheet for Form Responses on Google Forms.

Make sure you create a enter image description here

I used this function getIdFromUrl(url) from this enter image description here

Inside Drive: enter image description here

Files are moved inside the created folders: enter image description hereenter image description here

  • Related