LoginSignup
6
6

More than 5 years have passed since last update.

JSでファイルを読み込んで表示する方法

Last updated at Posted at 2015-02-21

貼付けたいファイルを画面に反映させる。
参考URL: https://developer.mozilla.org/ja/docs/Using_files_from_web_applications#Example.3A_Using_object_URLs_to_display_images


<input type="file" id="fileSelector" multiple accept="image/*" />

<ul id="fileContentList" style="list-style-type: none;"></ul>

<script>
  $(document).ready(function(){
    $('#fileSelector').on('change', function(evt){
      showImage(evt);
    });

    function showImage(evt){
      var files = evt.target.files; 

      if (!files) {
        alert("ファイルの読み込みに失敗しました、もう一度トライして下さい");
        return;
      }

      // javascript version
      var img_element = document.createElement('img');
          img_element.src = window.URL.createObjectURL(files[0]);
          img_element.width = 100;
          img_element.style.verticalAlign = "middle";
          img_element.style.margin = "4px 4px 4px 0";
          window.URL.revokeObjectURL(this.src);

      var span_element = document.createElement('span');
          span_element.innerHTML = files[0].name;

      var li_element = document.createElement('li');
          li_element.appendChild(img_element);
          li_element.appendChild(span_element);
      document.getElementById('fileContentList').appendChild(li_element);

      // jQuery version
      var fileContent = $('#fileContentList');

      var image = $('<img>').appendTo(fileContent);
          image.css({
            width: 100,
            verticalAlign: 'middle',
            margin: '4px 4px 4px 0'
          });
          image.attr('src', window.URL.createObjectURL(files[0]));

      var span = $('span');
          span.innerHTML = files[0].name;

      var li = $('li');
          li.append(image);
          li.append(span);

      fileContent.append(li);
    }
  });
</script>


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