FileReader.readAsText()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since January 2020.

readAsText() メソッドは、指定された Blob または File の内容を読み取るために使用します。読み取り操作が完了すると、 readyStateDONE に変わり、 loadend イベントが発生し、 result プロパティにはファイルの内容が文字列として格納されます。

メモ: Blob.text() メソッドは、ファイルをテキストとして読み取るための新しいプロミスベースの API です。

メモ: このメソッドは、ファイルの内容全体をメモリーに読み込みますので、巨大なファイルには適していません。巨大なファイルには readAsArrayBuffer() の方が適しています。

構文

js
readAsText(blob)
readAsText(blob, encoding)

引数

blob

メソッドで読み込む Blob または File オブジェクトです。

encoding 省略可

読み込みの際に使用する文字エンコーディングを指定する文字列です。この引数が指定されなかった場合は UTF-8 で解釈されます。

返値

なし (undefined)。

HTML

html
<input type="file" onchange="previewFile()" /><br />
<p class="content"></p>

JavaScript

js
function previewFile() {
  const content = document.querySelector(".content");
  const [file] = document.querySelector("input[type=file]").files;
  const reader = new FileReader();

  reader.addEventListener(
    "load",
    () => {
      // this will then display a text file
      content.innerText = reader.result;
    },
    false,
  );

  if (file) {
    reader.readAsText(file);
  }
}

結果

仕様書

Specification
File API
# readAsDataText

ブラウザーの互換性

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
readAsText

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

関連情報