Google フォームから Google ドライブにファイルをアップロードする

コーディング レベル: 初級
所要時間: 10 分
プロジェクトの種類: イベント ドリブン トリガーを使用した自動化

目標

  • ソリューションの機能を理解します。
  • Apps Script サービスがソリューション内でどのように機能するかを理解します。
  • スクリプトを設定します。
  • スクリプトを実行します。

このソリューションについて

Google フォームを使用して、Google ドライブにファイルを同時にアップロードして整理できます。 フォームには、アップロードするファイルとファイルの編成方法に関する入力が含まれます。

ファイルをアップロードするフォームのスクリーンショット

仕組み

設定関数により、アップロードされたすべてのファイルを保存するフォルダと、フォームが送信されるたびに起動するトリガーが作成されます。ユーザーがフォームに入力するときに、アップロードするファイルとファイルを保存するサブフォルダを選択します。ユーザーがフォームを送信すると、スクリプトは対応するサブフォルダにファイルを転送します。フォルダがまだ存在しない場合は、スクリプトによって作成されます。

Apps Script サービス

このソリューションでは、次のサービスを使用します。

  • スクリプト サービス - フォームが送信されるたびに配信されるトリガーを作成します。
  • プロパティ サービス - トリガーの重複を防ぐために、スクリプトがセットアップ中に作成するトリガーの ID を保存します。
  • ドライブ サービス - 設定中に、ドライブ内でのフォームの場所を取得し、同じ場所にフォルダを作成します。ユーザーがフォームを送信すると、ドライブ サービスはそのフォルダにファイルを転送し、選択した場合は指定されたサブフォルダに転送します。サブフォルダがまだ存在しない場合は、スクリプトによって作成されます。
  • フォーム サービス - ユーザーがフォームを送信した後に選択したファイルとフォルダ名を取得し、ドライブ サービスに送信します。

前提条件

このサンプルを使用するには、次の前提条件を満たす必要があります。

  • Google アカウント(Google Workspace アカウントの場合、管理者の承認が必要になる場合があります)。
  • インターネットにアクセスできるウェブブラウザ。

スクリプトを設定する

フォームを作成する

  1. forms.google.com にアクセスし、[空のアイコン ] をクリックします。
  2. [無題のフォーム] をクリックし、フォームの名前を「ドライブにファイルをアップロード」に変更します。
  3. [無題の質問] をクリックし、質問の名前を「サブフォルダ」に変更します。
  4. [サブフォルダ] の質問で、その他アイコン > [説明] をクリックします。
  5. [説明] に、「ファイルを保存するサブフォルダを選択」と入力します。<なし> を選択すると、ファイルは [Uploaded files] フォルダに保存されます。
  6. サブフォルダの質問に次のオプションを追加します。
    • <なし>
    • プロジェクト A
    • プロジェクト B
    • プロジェクト C
  7. 質問を必須にするには、[必須] をクリックします。
  8. 質問を追加アイコン をクリックします。
  9. [選択式] をクリックし、[ファイルのアップロード] を選択します。
  10. [続行] をクリックします。
  11. [質問] に「アップロードするファイル」と入力します。アップロードを許可するファイル形式と最大数を選択できます。
  12. 質問を必須にするには、[必須] をクリックします。

Apps Script プロジェクトを作成する

  1. フォームで、その他アイコン > [スクリプト エディタ] をクリックします。
  2. [無題のプロジェクト] をクリックし、プロジェクトの名前を「ドライブにファイルをアップロード」に変更します。
  3. 別のスクリプト ファイルを作成するには、ファイルを追加 > [スクリプト] をクリックします。ファイルに Setup という名前を付けます。
  4. 両方のスクリプト ファイルの内容を次の内容に置き換えます。

    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 constants
    const APP_TITLE = "Upload files to Drive from Forms";
    const APP_FOLDER_NAME = "Upload files to Drive (File responses)";
    
    // Identifies the subfolder form item
    const 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();
    }
    

スクリプトを実行する

  1. Apps Script エディタで、Setup.gs ファイルに切り替えます。
  2. 関数のプルダウンで、setUp を選択します。
  3. [実行] をクリックします。
  4. プロンプトが表示されたら、スクリプトを承認します。OAuth 同意画面に「このアプリは確認されていません」という警告が表示された場合は、[詳細設定] > [{プロジェクト名}(安全でない)に移動] を選択します。

  5. フォームに戻り、プレビュー アイコン プレビュー アイコン をクリックします。

  6. フォームでサブフォルダを選択し、ファイルをアップロードします。

  7. [送信] をクリックします。

  8. ドライブに移動し、[ドライブにファイルをアップロード(ファイル レスポンス)] フォルダを開きます。アップロードしたファイルは、フォームで選択したサブフォルダにあります。

協力者

このサンプルは、Google Developer Experts の協力により Google が保守しています。

次のステップ