3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

アップロードしたファイルをテキストで読み込む

Posted at

いつも忘れて検索しているので、メモ。<input type="file" />から選択されたファイルをテキストとして読み込む場合は、FileReaderのreadAsTextを使う。

サンプル

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title>ファイルをテキストで読み込むサンプル</title>
</head>
<body>
  <h1>ファイルをテキストで読み込むサンプル</h1>

  <input type="file" id="file" />
  <textarea id="textarea" readonly>
  </textarea>

  <script>
    const textarea = document.querySelector('#textarea');
    document.querySelector('#file').addEventListener('change', e => {
      if (e.target.files[0]) {
        const file = e.target.files[0];
        const reader = new FileReader();
        reader.onload = e => {
          textarea.value = e.target.result;
        };
        // BlobまたはFileをテキストとして読み込む
        // 第2引数にencodingを指定可能、
        // 指定しない場合はUTF8として読み込み
        reader.readAsText(file);
      }
    });
  </script>
</body>
</html>

3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?