File API、XMLHttpRequest、Drag and Drop... あなたに合った方法はどれ?
ブラウザからローカルテキストファイルを読み込む方法:JavaScript、File API、XMLHttpRequest
File APIは、HTML5で導入されたAPIで、ブラウザからローカルファイルを読み書きするための機能を提供します。最も一般的でシンプルな方法です。
手順
<input type="file">
要素を使って、ユーザーにファイルを選択させる。- 選択されたファイルオブジェクトを取得し、
readAsText()
メソッドを使ってファイル内容をテキスト形式で読み込む。 - 読み込んだテキストを、処理や表示に使用します。
例
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>ファイルを読み込む</title>
</head>
<body>
<input type="file" id="fileInput">
<button onclick="readFile()">ファイルを読み込む</button>
<div id="output"></div>
<script>
function readFile() {
const fileInput = document.getElementById('fileInput');
const file = fileInput.files[0];
if (file) {
const reader = new FileReader();
reader.onload = function(e) {
const text = e.target.result;
const output = document.getElementById('output');
output.textContent = text;
};
reader.readAsText(file);
} else {
alert('ファイルを選択してください。');
}
}
</script>
</body>
</html>
XMLHttpRequestは、ブラウザからWebサーバーへ非同期通信を行うためのAPIです。ローカルファイルにもアクセスできますが、File APIよりも複雑な方法です。
XMLHttpRequest
オブジェクトを作成し、open()
メソッドでファイルを読み込むための設定を行う。send()
メソッドを実行して、リクエストを送信する。onload
イベントハンドラで、レスポンスの処理を行う。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>ファイルを読み込む</title>
</head>
<body>
<button onclick="readFile()">ファイルを読み込む</button>
<div id="output"></div>
<script>
function readFile() {
const file = 'data.txt'; // 読み込むファイル名
const xhr = new XMLHttpRequest();
xhr.open('GET', file);
xhr.onload = function() {
if (xhr.status === 200) {
const text = xhr.responseText;
const output = document.getElementById('output');
output.textContent = text;
} else {
alert('ファイルの読み込みに失敗しました。');
}
};
xhr.send();
}
</script>
</body>
</html>
FileReader.readAsDataURL()
メソッドを使って、ファイル内容をBase64エンコードされたデータURI形式で取得する方法です。画像ファイルの読み込みなどに適しています。
- 取得したデータURIを、img要素の
src
属性などに設定して画像を表示したり、処理に使用したりします。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>ファイルを読み込む</title>
</head>
<body>
<input type="file" id="fileInput">
<button onclick="readFile()">ファイルを読み込む</button>
<img id="image">
<script>
function readFile() {
const fileInput = document.getElementById('fileInput');
const file = fileInput.files[0];
if (file) {
const reader = new FileReader();
reader.onload = function(e) {
const dataURL = e.target.result;
const image = document.getElementById('image');
image.src = dataURL;
};
reader.readAsDataURL(file);
} else {
alert('ファイルを選択してください。');
}
}
</
File API
HTML
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>ファイルを読み込む</title>
</head>
<body>
<input type="file" id="fileInput">
<button onclick="readFile()">ファイルを読み込む</button>
<div id="output"></div>
<script>
function readFile() {
const fileInput = document.getElementById('fileInput');
const file = fileInput.files[0];
if (file) {
const reader = new FileReader();
reader.onload = function(e) {
const text = e.target.result;
const output = document.getElementById('output');
output.textContent = text;
};
reader.readAsText(file);
} else {
alert('ファイルを選択してください。');
}
}
</script>
</body>
</html>
JavaScript
このコードは、以下の処理を行います。
- 選択されたファイルオブジェクトを取得し、
FileReader
オブジェクトを作成する。 FileReader
オブジェクトのonload
イベントハンドラを設定する。- 読み込んだテキストを、
div
要素のtextContent
プロパティに設定して表示する。
ポイント
readAsText()
メソッドは、非同期処理なので、onload
イベントハンドラで処理を行う必要があります。- ファイルのエンコーディングが異なる場合は、
encoding
オプションを指定して読み込むことができます。
XMLHttpRequest
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>ファイルを読み込む</title>
</head>
<body>
<button onclick="readFile()">ファイルを読み込む</button>
<div id="output"></div>
<script>
function readFile() {
const file = 'data.txt'; // 読み込むファイル名
const xhr = new XMLHttpRequest();
xhr.open('GET', file);
xhr.onload = function() {
if (xhr.status === 200) {
const text = xhr.responseText;
const output = document.getElementById('output');
output.textContent = text;
} else {
alert('ファイルの読み込みに失敗しました。');
}
};
xhr.send();
}
</script>
</body>
</html>
- ステータスコードが200であれば、
responseText
プロパティからファイル内容を取得して表示する。 - ステータスコードが200でない場合は、エラーメッセージを表示する。
open()
メソッドの第一引数には、リクエストメソッド(GET、POSTなど)を、第二引数には読み込むファイルのパスを指定します。onload
イベントハンドラ内で、エラー処理を行うことを忘れずに。
FileReader.readAsDataURL
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>ファイルを読み込む</title>
</head>
<body>
<input type="file" id="fileInput">
<button onclick="readFile()">ファイルを読み込む</button>
<img id="image">
<script>
function readFile() {
const fileInput = document.getElementById('fileInput');
const file = fileInput.files[0];
if (file) {
const reader = new FileReader();
reader.onload = function(e) {
const dataURL = e.target.result;
const image = document.getElementById('image');
image.src = dataURL;
};
reader.readAsDataURL(file);
} else {
alert('ファイルを選択してください。
ブラウザからローカルテキストファイルを読み込む:その他の方法
Drag and Drop
HTML5のDrag and Drop APIを利用して、ファイルをブラウザへドラッグ&ドロップすることで読み込む方法です。
<div>
要素にdrop
イベントを設定し、ドロップされたファイルの処理を行う。DataTransfer
オブジェクトからファイルオブジェクトを取得し、readAsText()
などのメソッドを使ってファイル内容を読み込む。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>ファイルをドラッグ&ドロップで読み込む</title>
</head>
<body>
<div id="dropzone">ファイルをここにドラッグ&ドロップしてください</div>
<div id="output"></div>
<script>
const dropzone = document.getElementById('dropzone');
dropzone.addEventListener('drop', function(e) {
e.preventDefault();
const files = e.dataTransfer.files;
if (files.length > 0) {
const file = files[0];
const reader = new FileReader();
reader.onload = function(e) {
const text = e.target.result;
const output = document.getElementById('output');
output.textContent = text;
};
reader.readAsText(file);
}
});
</script>
</body>
</html>
dropzone
要素にondragover
イベントを設定することで、ドラッグしているファイルが要素の上にあることを示すことができます。- ファイルのドロップ後、
DataTransfer
オブジェクトから取得できる情報は、ファイル名、ファイルサイズ、MIMEタイプなどがあります。
Web Workerは、メインスレッドとは独立して実行されるスレッドです。ファイル読み込みのような時間がかかる処理をメインスレッドから切り離すことで、ブラウザの応答性を向上させることができます。
- Web Workerを作成し、ファイル読み込みの処理を記述する。
- メインスレッドからWorkerへメッセージを送信して、ファイル読み込みを開始する。
- Workerから読み込み完了のメッセージを受け取ったら、結果を処理する。
worker.js
addEventListener('message', function(e) {
const file = e.data.file;
const reader = new FileReader();
reader.onload = function(e) {
const text = e.target.result;
postMessage({ result: text });
};
reader.readAsText(file);
});
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>Web Workerでファイルを読み込む</title>
</head>
<body>
<button onclick="readFile()">ファイルを読み込む</button>
<div id="output"></div>
<script>
const worker = new Worker('worker.js');
worker.addEventListener('message', function(e) {
const text = e.data.result;
const output = document.getElementById('output');
output.textContent = text;
});
function readFile() {
const fileInput = document.createElement('input');
fileInput.type = 'file';
fileInput.addEventListener('change', function(e) {
const file = e.target.files[0];
worker.postMessage({ file: file });
});
fileInput.click();
}
</script>
</body>
</html>
- Web Workerは、メインスレッドとは異なるコンテキストで実行されるため、共有変数などは直接アクセスできません。メッセージパッシングを使って、メインスレッドとWorker間で通信を行う必要があります。
- Web Workerは、JavaScript以外の言語(C++、WebAssemblyなど)で記述することもできます。
Node.js (Electron)
Node.jsは、JavaScriptで実行できるサーバーサイドランタイム環境です。Electronは、Node.jsとChromiumエンジンを組み合わせたフレームワークで、デスクトップアプリケーションを開発することができます。
- Electronアプリを開発し、Node.jsの
fs
モジュールを使ってファイルを読み込む。 - アプリをビルドして、ユーザーが実行できるようにする。
javascript file-io xmlhttprequest