Upload files to Google Drive from Google Forms  |  Apps Script  |  Google for Developers (2024)

  • Home
  • Google Workspace
  • Apps Script
  • Samples
Stay organized with collections Save and categorize content based on your preferences.

Coding level: Beginner
Duration: 10 minutes
Project type: Automation with an event-driven trigger

Objectives

  • Understand what the solution does.
  • Understand what the Apps Script services do within thesolution.
  • Set up the script.
  • Run the script.

About this solution

Simultaneously upload and organize files in Google Drive using Google Forms.The form includes inputs for the files to upload and for how the filesshould be organized.

Upload files to Google Drive from Google Forms | Apps Script | Google for Developers (3)

Upload files to Google Drive from Google Forms | Apps Script | Google for Developers (4)

How it works

A setup function creates a folder to store all uploaded files and a trigger thatfires each time someone submits the form. When a user fills out the form, theychoose files to upload and a subfolder to store the files in. Once the usersubmits the form, the script routes the files to the corresponding subfolder. Ifthe folder doesn't exist yet, the script creates it.

Apps Script services

This solution uses the following services:

  • Script service–Creates the trigger thatfires each time someone submits the form.
  • Properties service–Stores the ID of thetrigger that the script creates during setup to prevent duplicate triggers.
  • Drive service–During setup,gets the form's location in Drive and creates a folder in thesame location. When a user submits the form, Drive serviceroutes the files to that folder, and ifselected, a designated subfolder. If the subfolder doesn't exist yet, thescript creates it.
  • Forms service–Gets the filesand folder name the user chose after they submit the form and sends it toDrive service.

Prerequisites

To use this sample, you need the following prerequisites:

  • A Google Account (Google Workspace accounts mightrequire administrator approval).
  • A web browser with access to the internet.

Set up the script

Create the form

  1. Go to forms.google.com and click Blankadd.
  2. Click Untitled form and rename the form to Upload files to Drive.
  3. Click Untitled question and rename the question to Subfolder.
  4. On the Subfolder question, click More more_vert> Description.
  5. For Description, enter Select the subfolder to store your files in. Ifyou select <None>, the files are stored in the Uploaded files folder.
  6. Add the following options to the Subfolder question:
    • <none>
    • Project A
    • Project B
    • Project C
  7. To make the question required, click Required.
  8. Click Add question add_circle.
  9. Click Multiple choice and select File upload.
  10. Click Continue.
  11. For Question, enter Files to upload. You can choose the file typesand maximum number of files you want to let people upload.
  12. To make the question required, click Required.

Create the Apps Script project

  1. From the form, click More more_vert> Script editor.
  2. Click Untitled project and rename the project to Upload files toDrive.
  3. To create another script file, click Add a fileadd> Script. Name the file Setup.
  4. Replace the content of both script files with thefollowing content:

    Code.gs

    solutions/automations/upload-files/Code.js

    // TODO Before you start using this sample, you must run the setUp() // function in the Setup.gs file.// Application constantsconst APP_TITLE = "Upload files to Drive from Forms";const APP_FOLDER_NAME = "Upload files to Drive (File responses)";// Identifies the subfolder form itemconst APP_SUBFOLDER_ITEM = "Subfolder";const APP_SUBFOLDER_NONE = "<None>";/** * Gets the file uploads from a form response and moves files to the corresponding subfolder. *  * @param {object} event - Form submit. */function onFormSubmit(e) { try { // Gets the application root folder. var destFolder = getFolder_(APP_FOLDER_NAME); // Gets all form responses. let itemResponses = e.response.getItemResponses(); // Determines the subfolder to route the file to, if any. var subFolderName; let dest = itemResponses.filter((itemResponse) => itemResponse.getItem().getTitle().toString() === APP_SUBFOLDER_ITEM); // Gets the destination subfolder name, but ignores if APP_SUBFOLDER_NONE was selected; if (dest.length > 0) { if (dest[0].getResponse() != APP_SUBFOLDER_NONE) { subFolderName = dest[0].getResponse(); } } // Gets the subfolder or creates it if it doesn't exist. if (subFolderName != undefined) { destFolder = getSubFolder_(destFolder, subFolderName) } console.log(`Destination folder to use: Name: ${destFolder.getName()} ID: ${destFolder.getId()} URL: ${destFolder.getUrl()}`) // Gets the file upload response as an array to allow for multiple files. let fileUploads = itemResponses.filter((itemResponse) => itemResponse.getItem().getType().toString() === "FILE_UPLOAD") .map((itemResponse) => itemResponse.getResponse()) .reduce((a, b) => [...a, ...b], []); // Moves the files to the destination folder. if (fileUploads.length > 0) { fileUploads.forEach((fileId) => { DriveApp.getFileById(fileId).moveTo(destFolder); console.log(`File Copied: ${fileId}`) }); } } catch (err) { console.log(err); }}/** * Returns a Drive folder under the passed in objParentFolder parent * folder. Checks if folder of same name exists before creating, returning  * the existing folder or the newly created one if not found. * * @param {object} objParentFolder - Drive folder as an object. * @param {string} subFolderName - Name of subfolder to create/return. * @return {object} Drive folder */function getSubFolder_(objParentFolder, subFolderName) { // Iterates subfolders of parent folder to check if folder already exists. const subFolders = objParentFolder.getFolders(); while (subFolders.hasNext()) { let folder = subFolders.next(); // Returns the existing folder if found. if (folder.getName() === subFolderName) { return folder; } } // Creates a new folder if one doesn't already exist. return objParentFolder.createFolder(subFolderName) .setDescription(`Created by ${APP_TITLE} application to store uploaded Forms files.`);}

    Setup.gs

    solutions/automations/upload-files/Setup.js

    // TODO You must run the setUp() function before you start using this sample./**  * The setUp() function performs the following: * - Creates a Google Drive folder named by the APP_FOLDER_NAME * variable in the Code.gs file. * - Creates a trigger to handle onFormSubmit events. */function setUp() { // Ensures the root destination folder exists. const appFolder = getFolder_(APP_FOLDER_NAME); if (appFolder !== null) { console.log(`Application folder setup. Name: ${appFolder.getName()} ID: ${appFolder.getId()} URL: ${appFolder.getUrl()}`) } else { console.log(`Could not setup application folder.`) } // Calls the function that creates the Forms onSubmit trigger. installTrigger_();}/**  * Returns a folder to store uploaded files in the same location * in Drive where the form is located. First, it checks if the folder * already exists, and creates it if it doesn't. * * @param {string} folderName - Name of the Drive folder.  * @return {object} Google Drive Folder */function getFolder_(folderName) { // Gets the Drive folder where the form is located. const ssId = FormApp.getActiveForm().getId(); const parentFolder = DriveApp.getFileById(ssId).getParents().next(); // Iterates through the subfolders to check if folder already exists. // The script checks for the folder name specified in the APP_FOLDER_NAME variable. const subFolders = parentFolder.getFolders(); while (subFolders.hasNext()) { let folder = subFolders.next(); // Returns the existing folder if found. if (folder.getName() === folderName) { return folder; } } // Creates a new folder if one doesn't already exist. return parentFolder.createFolder(folderName) .setDescription(`Created by ${APP_TITLE} application to store uploaded files.`);}/** * Installs trigger to capture onFormSubmit event when a form is submitted. * Ensures that the trigger is only installed once. * Called by setup(). */function installTrigger_() { // Ensures existing trigger doesn't already exist. let propTriggerId = PropertiesService.getScriptProperties().getProperty('triggerUniqueId') if (propTriggerId !== null) { const triggers = ScriptApp.getProjectTriggers(); for (let t in triggers) { if (triggers[t].getUniqueId() === propTriggerId) { console.log(`Trigger with the following unique ID already exists: ${propTriggerId}`); return; } } } // Creates the trigger if one doesn't exist. let triggerUniqueId = ScriptApp.newTrigger('onFormSubmit') .forForm(FormApp.getActiveForm()) .onFormSubmit() .create() .getUniqueId(); PropertiesService.getScriptProperties().setProperty('triggerUniqueId', triggerUniqueId); console.log(`Trigger with the following unique ID was created: ${triggerUniqueId}`);}/** * Removes all script properties and triggers for the project. * Use primarily to test setup routines. */function removeTriggersAndScriptProperties() { PropertiesService.getScriptProperties().deleteAllProperties(); // Removes all triggers associated with project. const triggers = ScriptApp.getProjectTriggers(); for (let t in triggers) { ScriptApp.deleteTrigger(triggers[t]); }}/** * Removes all form responses to reset the form. */function deleteAllResponses() { FormApp.getActiveForm().deleteAllResponses();}

Run the script

  1. In the Apps Script editor, switch to the Setup.gs file.
  2. In the function dropdown, select setUp.
  3. Click Run.
  4. When prompted, authorize the script.If the OAuth consent screen displays the warning, This app isn't verified,continue by selecting Advanced >Go to {Project Name} (unsafe).

  5. Return to the form and clickPreview Upload files to Google Drive from Google Forms | Apps Script | Google for Developers (5).

  6. On the form, select a subfolder and upload a file.

  7. Click Submit.

  8. Go to Drive and open the Upload files toDrive (File responses) folder.Your uploaded files are in the subfolder you selected on the form.

Contributors

This sample is maintained by Google with the help of Google Developer Experts.

Next steps

  • Event-driven triggers
  • Forms service reference

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2024-09-06 UTC.

Upload files to Google Drive from Google Forms  |  Apps Script  |  Google for Developers (2024)
Top Articles
If you can't add a card to Apple Wallet to use with Apple Pay
Get the most life from your Android device's battery
Where are the Best Boxing Gyms in the UK? - JD Sports
Combat level
Clafi Arab
MADRID BALANZA, MªJ., y VIZCAÍNO SÁNCHEZ, J., 2008, "Collares de época bizantina procedentes de la necrópolis oriental de Carthago Spartaria", Verdolay, nº10, p.173-196.
Danielle Longet
Clairememory Scam
What Does Dwb Mean In Instagram
Mid90S Common Sense Media
Housework 2 Jab
The most iconic acting lineages in cinema history
7 Fly Traps For Effective Pest Control
Define Percosivism
Costco Gas Foster City
Khiara Keating: Manchester City and England goalkeeper convinced WSL silverware is on the horizon
Nail Salon Goodman Plaza
Publix Super Market At Rainbow Square Shopping Center Dunnellon Photos
20 Different Cat Sounds and What They Mean
Halo Worth Animal Jam
Tuw Academic Calendar
Biografie - Geertjan Lassche
What is Software Defined Networking (SDN)? - GeeksforGeeks
Craigslist Boerne Tx
Where Can I Cash A Huntington National Bank Check
Sun Haven Pufferfish
#scandalous stars | astrognossienne
Kvoa Tv Schedule
Carespot Ocoee Photos
Ljw Obits
Reborn Rich Ep 12 Eng Sub
Craigslist Georgia Homes For Sale By Owner
Soulstone Survivors Igg
Craigslist Summersville West Virginia
Empires And Puzzles Dark Chest
Top 25 E-Commerce Companies Using FedEx
Tryst Houston Tx
Lonely Wife Dating Club בקורות וחוות דעת משתמשים 2021
Lacy Soto Mechanic
Immobiliare di Felice| Appartamento | Appartamento in vendita Porto San
Mathews Vertix Mod Chart
2024-09-13 | Iveda Solutions, Inc. Announces Reverse Stock Split to be Effective September 17, 2024; Publicly Traded Warrant Adjustment | NDAQ:IVDA | Press Release
Craigslist Woodward
Honkai Star Rail Aha Stuffed Toy
Reli Stocktwits
Nearest Wintrust Bank
F9 2385
Diamond Spikes Worth Aj
M Life Insider
sin city jili
O.c Craigslist
Land of Samurai: One Piece’s Wano Kuni Arc Explained
Latest Posts
Article information

Author: Rev. Leonie Wyman

Last Updated:

Views: 5566

Rating: 4.9 / 5 (79 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Rev. Leonie Wyman

Birthday: 1993-07-01

Address: Suite 763 6272 Lang Bypass, New Xochitlport, VT 72704-3308

Phone: +22014484519944

Job: Banking Officer

Hobby: Sailing, Gaming, Basketball, Calligraphy, Mycology, Astronomy, Juggling

Introduction: My name is Rev. Leonie Wyman, I am a colorful, tasty, splendid, fair, witty, gorgeous, splendid person who loves writing and wants to share my knowledge and understanding with you.