1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Google Apps Script で Google Drive にファイルをアップロードできるフォームを作成する(Base64方式)

Last updated at Posted at 2025-11-30

はじめに

業務効率化でGoogleフォームを使う機会は多いが、「ファイルのアップロード」機能を使おうとすると、「回答者にGoogleアカウントでのログインが必須になる」という壁にぶつかる。
Google アカウントを持っているユーザーしかアクセスしないなら問題ありませんが、アカウントを持っていないの人からはファイルを集めることができない。

そこで、Google Apps Script (GAS) と HTML を使って、「誰でも(ログイン不要で)」「スマホから」「画像をアップロードできる」フォームを自作した。

仕組みの概要

GASの google.script.run は、HTML上の File オブジェクトを直接サーバー側に送ることができない。そのため、以下のような手順を踏む必要がある。

  • Client (HTML/JS): でファイルを選択
  • Client (HTML/JS): FileReader を使い、ファイルを Data URL (Base64文字列) に変換
  • Communication: google.script.run で Base64文字列をGAS側に送信
  • Server (GAS): 受け取った文字列を Utilities.base64Decode でデコードし、Blob化して Google Drive に保存

実装コード

1. HTML / JavaScript (クライアント側)

ポイントは FileReader を使ってファイルを非同期で読み込み、読み込み完了後に送信データに追加している点です

<!DOCTYPE html>
<html>
  <head>
    <base target="_top" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  </head>
  <body>
    <form id="uploadForm">
      <label>
        ユーザー名:
        <input type="text" name="userName" required />
      </label>

      <label>
        添付ファイル:
        <input type="file" name="attachmentFile" required />
      </label>

      <button type="button" onclick="handleFormSubmit()">送信</button>
    </form>

    <script>
      function handleFormSubmit() {
        const form = document.getElementById('uploadForm');
        const formData = {
          userName: form.userName.value,
        };
        const fileInput = form.attachmentFile;
        if (fileInput.files.length === 0) {
          alert('ファイルを選択してください');
          return;
        }
        const file = fileInput.files[0];
        const reader = new FileReader();

        reader.onload = function (e) {
          const fileData = {
            fileName: file.name,
            mimeType: file.type,
            data: e.target.result,
          };

          google.script.run
            .withSuccessHandler(onSuccess)
            .withFailureHandler(onFailure)
            .processForm(formData, fileData);
        };

        reader.readAsDataURL(file);
      }

      function onSuccess(res) {
        alert('送信完了!保存先URL: ' + res.url);
        document.getElementById('uploadForm').reset();
      }

      function onFailure(e) {
        alert('エラーが発生しました: ' + e);
      }
    </script>
  </body>
</html>

2. Google Apps Script (サーバー側)

受け取ったBase64文字列から不要なヘッダー部分(例: data:image/png;base64,)を取り除き、デコードして保存します。

function doGet() {
  return HtmlService.createTemplateFromFile('index')
    .evaluate()
    .addMetaTag('viewport', 'width=device-width, initial-scale=1')
    .setTitle('ファイルアップロードフォーム');
}

function processForm(formData, fileData) {
  try {
    const folderId = 'YOUR_FOLDER_ID_HERE';
    const folder = DriveApp.getFolderById(folderId);
    const base64Data = fileData.data.split(',')[1];
    const decodedBlob = Utilities.newBlob(
      Utilities.base64Decode(base64Data),
      fileData.mimeType,
      fileData.fileName,
    );

    const newFileName = formData.userName + '_' + fileData.fileName;
    decodedBlob.setName(newFileName);

    const file = folder.createFile(decodedBlob);
    return { success: true, url: file.getUrl() };
  } catch (e) {
    throw new Error(e.toString());
  }
}

デプロイ時の最重要ポイント

このフォームを「Googleアカウントを持っていない人」に使ってもらうためには、デプロイ設定が非常に重要。

  • GASエディタ右上の「デプロイ」 > 「新しいデプロイ」
  • 次のユーザーとして実行: 「自分 (Me)」
    • ここを「ウェブアプリケーションにアクセスしているユーザー」にしてしまうと、投稿者にDriveへの書き込み権限がないためエラーになる
  • アクセスできるユーザー: 「全員 (Anyone)」
    • これでログイン不要の公開フォームになる

複数ファイルの対応

上記の例は1ファイルですが、複数の input type="file" がある場合は、JavaScript側で Promise.all を使って全ての FileReader の読み込みを待ってから google.script.run を実行するように実装するとスムーズ

まとめ

Base64変換を挟むことで、Googleフォームでは実現できない「ログイン不要のファイル収集」が可能になる。
活用範囲は非常に広いです。ぜひ試してみてください。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?