15
19

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 で ローカルの画像をプレビュー

Posted at

ローカルの画像ファイルを表示する

#コード

sample.html


<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title>画像表示テスト</title>
</head>
<body>
<img src="" id="preview">
<input type="file" accept="image/*" id="getfile">
<script>
var file = document.querySelector('#getfile');

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

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

document.querySelector('#preview').src = reader.result;
img要素のsrcに読み込んだファイルのデータを渡せば表示できる

##実行結果
imgReader.png

15
19
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
15
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?