Uploading a file to GoogleDrive using GoogleAppsScript(GAS)

Hello, I’m “Iori Nitta.”

This time, I will create a simple application using Google Apps Script (GAS) to upload files to Google Drive.

code.gs

function doGet() {
  const htmlOutput = HtmlService.createTemplateFromFile('index').evaluate();
  return htmlOutput;
}

// post Data from Html
function postForm(formObject) {
  const blob = formObject.file;

  const folder_id = '< GoogleDrive Folder ID >'; // Google Drive's FolderID
  const folder = DriveApp.getFolderById(folder_id);
  folder.createFile(blob);
}

index.html

<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <base target="_top">

    <title>
      Gasを使用してファイルをGoogleDriveにあげる
    </title>
    <?!=HtmlService.createHtmlOutputFromFile('style').getContent();?>
    <?!=HtmlService.createHtmlOutputFromFile('script').getContent();?>
  </head>
  <body>
    <h1>GASでファイルをGoogleDriveにアップロード</h1>
    <h3>ファイルを選択してください(50MBまで)</h3>
    <form id="upload_form" onsubmit="handleFormSubmit(this)">
      <div>
        <input id="file_input" name="file" type="file"><br>
      </div>
      <div>
        <input id="upload_button" type="submit" value="アップロード">
      </div>
    </form>
    <div id="message" class="center"></div>

    <span>
      Created by: <a href="https://nitta-iori.com/">新田いおり</a>
    </span>
  </body>
</html>

style.html

<style>
  body {
    text-align: center;
  }
</style>

script.html

<script>
  function preventFormSubmit() {
    const upload_form = document.getElementById("upload_form");
    upload_form.addEventListener("submit", e => {
      e.preventDefault();
    });
  }

  // post Data
  function handleFormSubmit(formObject) {
    const file = formObject.file;
    const len = file.files.length;
    const size = file.files[0].size;
    const maxSize = 1024 * 1024 * 50; // max 50MB

    if (len === 1 && size <= maxSize) {
      const message_div = document.getElementById("message");
      message_div.innerHTML="Uploading ...";
      google.script.run.withSuccessHandler(updateMessage).postForm(formObject);
    }
  }

  // finished upload
  function updateMessage() {
    const message_div = document.getElementById("message");
    message_div.innerHTML = "Success Uploaded.";
  }

  window.addEventListener("load", preventFormSubmit);

</script>


With this, we have completed a simple application to send files to Google Drive.

By deploying it to a publicly accessible site, you can create a convenient platform for sharing videos and files with friends.

I hope this helps those who are using GAS for development. Thank you for your support, and please feel free to reach out in the future.

Leave a Comment