22
23

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.

HTML5 / JavaScript でテキストファイルを読み込んで表示

Last updated at Posted at 2015-06-21

ローカルにあるテキストファイルを読み込んで表示させる

コード

sample.html

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title>File 読み込みテスト</title>
</head>
<body>
<pre id="preview" ></pre>
<input type="file" id="getfile" accept="text/*">
<script>
var file = document.querySelector('#getfile');

file.onchange = function (){
  var fileList = file.files;
  //読み込み
  var reader = new FileReader();
  reader.readAsText(fileList[0]);

  //読み込み後
  reader.onload = function  () {
    document.querySelector('#preview').textContent = reader.result;
  };
};
</script> 
</body>
</html>

input要素のaccept属性にはワイルドカード * を使用することができます。

実行結果

file_img1.png

22
23
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
22
23

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?