javascript フォームに入力した内容をファイルとしてダウンロードする
- 作成日 2022.03.02
- javascript
- javascript

javascriptで、フォームに入力した内容をファイルとしてダウンロードするサンプルコードを掲載してます。ブラウザはchromeを使用しています。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 98.0.4758.102
ファイルとしてダウンロード
ファイルとしてダウンロードするには、以下の「html」の「download属性」を使用します。
<a href="hoge.jpg" download="hoge_download.jpg">
これを、javascriptで作成してフォームに入力された値をテキストファイルとしてダウンロードしてみます。
<textarea id="text">abc</textarea>
<script>
'use strict'
function download(txt) {
const blob = new Blob([txt], {type: 'text/plain'});
const url = URL.createObjectURL(blob);
// aタグ作成
const a = document.createElement("a");
document.body.appendChild(a);
a.download = 'foo.txt';
a.href = url;
// クリック後に削除
a.click();
a.remove();
}
document.getElementById("btn").onclick = function () {
let text = document.getElementById("text").value;
download(text);
};
</script>
実行結果

また、以下のコードは、
document.getElementById("btn").onclick = function () {
let text = document.getElementById("text").value;
download(text);
};
document.getElementByIdを省略して記述することも可能です。関数もアロー化してます。
btn.onclick = () => {
download(text.value);
};
サンプルコード
以下は、
「実行」ボタンをクリックした際に、フォームに入力した値をファイル名としてファイルをダウンロードするサンプルコードとなります。
※cssには「tailwind」を使用して、アロー関数で関数は定義してます。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>mebeeサンプル</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.tailwindcss.com"></script>
</head>
<script>
const hoge = (txt) => {
const blob = new Blob([txt], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
// aタグ作成
const a = document.createElement("a");
document.body.appendChild(a);
a.download = txt + '.txt';
a.href = url;
// クリック後に削除
a.click();
a.remove();
}
window.onload = () => {
btn.onclick = () => { hoge(txt.value) };
}
</script>
<body>
<div class="container mx-auto my-56 w-64 px-4">
<div id="sample" class="flex flex-col justify-center">
<h1 class="font-semibold text-rose-500 text-lg mr-auto">ダウンロード</h1>
<input
class="mb-2 shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
id="txt" type="txt">
<button id="btn"
class="mb-2 md:mb-0 bg-transparent hover:bg-violet-500 text-violet-700 font-semibold hover:text-white py-2 px-4 border border-violet-500 hover:border-transparent rounded">
実行
</button>
</div>
</div>
</body>
</html>
実行結果を確認すると、ダウンロードされていることが確認できます。

-
前の記事
jquery 指定したhtmlタグの親htmlタグを削除していく 2022.03.01
-
次の記事
python PySimpleGUIのMenuBarでメニューを構築する 2022.03.02
コメントを書く