20
28

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.

複数ファイルアップロードで、アップロード前に画像とファイル名を表示させるサンプル

Last updated at Posted at 2016-02-14
スクリーンショット 2016-02-14 14.05.20.png

上の絵のように、ファイルを選択したタイミングで画面にサムネイルとファイル名を表示させます。
jQueryを使わずJavaScriptだけで書いているので、少々長いです。。

<input multiple="multiple" name="article_attachments[image_file_name][]" type="file" id="article_image_file_name">
<output id="list"></output>
<script>
  document.getElementById('article_image_file_name').onchange = function(event){
    initializeFiles();

    var files = event.target.files;

    for (var i = 0, f; f = files[i]; i++) {
      var reader = new FileReader;
      reader.readAsDataURL(f);

      reader.onload = (function(theFile) {
        return function (e) {
          var div = document.createElement('div');
          div.className = 'reader_file';
          div.innerHTML = '<div class="reader_title">' + encodeURIComponent(theFile.name) + '</div>';
          div.innerHTML += '<img class="reader_image" src="' + e.target.result + '" />';
          document.getElementById('list').insertBefore(div, null);
        }
      })(f);
    }
  };

  function initializeFiles() {
    document.getElementById('list').innerHTML = '';
  }
</script>
custom.scss
.reader_file {
  float: left;
  padding: 10px;
  width: 20%;
}
.reader_image {
  width: 80%;
}
.reader_title {
}

以上です。ありがとうございます。

20
28
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
20
28

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?