JavaScript:ドラッグ&ドロップでファイルを読み込む方法

テキストファイルをテキストエリアにドラッグ&ドロップすると、ファイルの内容がテキストエリアに表示されます。 以下のテキストエリアで試すことができます。(Shift_JIS 以外でエンコードされていると文字化けするので注意してください)

プログラムは次のようになります。

readByDragDrop.html

<!doctype html>
<html>
<body>

<textarea id="TextArea" cols="100" rows="20" ondragover="handleOnDragOver();" ondrop="handleOnDrop(displayText);">
Drag & drop here.
</textarea>

<script>
function handleOnDragOver() {
  event.preventDefault();
}

function handleOnDrop(handleOnLoad) {
  event.preventDefault();
  const files = event.dataTransfer.files;
  const fileReader = new FileReader();
  fileReader.readAsText(files[0], "shift-jis"); // euc, utf-8, utf-16
  fileReader.addEventListener("load", function () { handleOnLoad(this); });
}

function displayText(fileReader) {
  document.getElementById("TextArea").innerHTML = fileReader.result;
}
</script>

</body>
</html>
 

参考サイト