LoginSignup
4
1

GASで作成したファイルをダウンロードする

Last updated at Posted at 2023-12-01

Agenda

  • はじめに

  • やりたいこと

  • どう実現するか

  • 実装

  • できた

  • さいごに

はじめに

今年7月入社のO84です
最近Turing Completeってゲームにドハマりしてます

やりたいこと

  1. GASで生成した文字列をテキストファイルに変換
  2. Google Driveを経由せずに上記ファイルをダウンロード

どう実現するか

Blob型1に変換すればファイルとしてダウンロードできるっぽい

JavaScript(ECMA)で定義されているBlobはGASに実装されてない2らしいので、
サーバ側でBlobに変換するとクライアントに渡すのがめんどくさそう3

サーバからはファイル名と中身を文字列で渡し、クライアント側でファイルに変換する方法でやってみる

実装

サーバ側

main.js
// スプレッドシートから開きたい
function onOpen() {
  const ui = SpreadsheetApp.getUi();
  const menu = ui.createMenu('自作ツール');
  menu.addItem('Download', 'showDialog');
  menu.addToUi();
}

function showDialog() {
  const html = HtmlService.createTemplateFromFile('download')
    .evaluate()
    .setWidth(400)
    .setHeight(300);
  SpreadsheetApp.getUi().showModalDialog(html, 'Download');
}

// こいつをクライアントから実行させる
function getFile() {
  return file = {
    filename: "任意のファイル名.txt",
    text: "任意の\n文字列",
  };
}

クライアント側

download.html
<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <div id="downloadLinks"></div>
    <script type='text/javascript'>
      window.addEventListener('load', function() {
        const element = document.getElementById('downloadLinks');
        // ここでサーバ側のgetFile関数を実行
        google.script.run
          .withSuccessHandler(function(file) {
            // 文字列をBlob型にする
            const blob = new Blob([file.text], {type: 'text/plain'});
            
            // ダウンロードリンクを作成
            const link = document.createElement('a');
            link.download = file.filename;
            link.text = file.filename;
            link.href = window.URL.createObjectURL(blob);
            
            // リンクを子要素として追加
            element.appendChild(link);
            element.appendChild(document.createElement('br'));
          })
          .withFailureHandler()
          .getFile();
      });
    </script>
  </body>
</html>

できた

dekita.png

さいごに

一緒に働く仲間を募集中です!

リンクラフト株式会社では、組織拡大に伴い積極的な採用活動を行っています。
少しでも興味がある方はぜひご連絡ください。

▽会社ホームページ
https://lincraft.co.jp/

▽SNS
X (旧Twitter)
Instagram
Facebook

▽ご応募はこちらより
https://lincraft.co.jp/recruit

※カジュアル面談も受付中です。ご希望の方はHPのお問い合わせフォームよりご連絡ください。

  1. Mozilla

  2. GAS の Blob とファイル変換まとめ

  3. Google Workspace

4
1
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
4
1