テキストエリアに入力したテキストをローカルにダウンロードしたい
コード.gs
function doGet() {
return HtmlService.createHtmlOutputFromFile("index");
}
|
意訳この機能がやること 指定したHTMLファイルを表示する |
index.html
<!DOCTYPE html>
<html>
<body>
<textarea id="ta"></textarea><br>
<input type="text" id="file_name" value="ファイル名">
<input type="text" id="content_type" value="text/plain"><br>
<button id="button">Download</button>
<script>
var download_button = document.getElementById("button");
download_button.onclick = download;
function download() {
var data = document.getElementById("ta").value;
var file_name = document.getElementById("file_name").value;
var content_type = document.getElementById("content_type").value;
var blob = new Blob([data], {"type":content_type});
var link = document.createElement("a");
link.download = file_name;
link.href = window.URL.createObjectURL(blob);
link.click();
}
</script>
</body>
</html>
|
意訳テキスト入力エリア ファイル名を入れるテキストボックス ContentTypeを指定するテキストボックス ダウンロードボタン idがbuttonの要素を取得して クリックされたらdownloadを実行する この機能がやること テキストエリアの値を取得して ファイル名を取得して content_typeを取得して Blobに入れて a要素を作成して ダウンロードするファイル名に指定して URLを作成して クリックしてダウンロードする |
参考
window.URL.createObjectURL
https://developer.mozilla.org/ja/docs/Web/API/URL/createObjectURL
<a>
https://developer.mozilla.org/ja/docs/Web/HTML/Element/a
window.URL.createObjectURL
https://developer.mozilla.org/ja/docs/Web/API/URL/createObjectURL
<a>
https://developer.mozilla.org/ja/docs/Web/HTML/Element/a