LoginSignup
11
7

More than 5 years have passed since last update.

<input type="file"> で入力された画像をサムネイル表示する(Pure JS)

Posted at

概要

画像のアップロードをする前にユーザが選択した画像をサムネイル表示する機能をライブラリを使わずに実装します。

実装

index.html
<input type="file" onchange="onChangeFileInput(this)">
<div>
  <img id="thumbnail" accept="image/*" src="/img/icon_add.png">
</div>
script.js
const onChangeInputFile = (e) => {
  if (e.target.files && e.target.files[0]) {
    const reader = new FileReader();
    reader.onload = function(e) {
      document.getElementById('thumbnail').setAttribute('src', e.target.result);
    };
    reader.readAsDataURL(e.target.files[0]);
  }
};
style.css
#thumbnail {
  height: 100px;
  max-width: 100px;
  margin: 10px;
  border: solid thin lightgray;
  border-radius: 5px;
}

ファイルが選択されていない状態だと不自然なぺしゃんこ四角形ができるので、100×100 の画像(icon_add.png)をセットしています。

利用例

before.png
 :point_down:
after.png

※ イラストの出典: 手巻き寿司のイラスト(いらすとや)

参考

11
7
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
11
7