IK.AM

@making's tech note


HTML5でファイルをドラッグ&ドロップして画像を表示するサンプル

🗃 {Programming/JavaScript/HTML5/File}
🏷 HTML5 🏷 JavaScript 
🗓 Updated at 2014-04-10T17:31:57Z  🗓 Created at 2014-04-10T17:31:57Z   🌎 English Page

ここにファイルをドロップ

CSS


.thumb {
  height: 75px;
  border: 1px solid #000;
  margin: 10px 5px 0 0;
}

#drop_zone {
  border: 2px dashed #bbb;
  -moz-border-radius: 5px;
  -webkit-border-radius: 5px;
  border-radius: 5px;
  padding: 25px;
  text-align: center;
  font: 20pt bold 'Vollkorn';
  color: #bbb;
}

HTML

<div id="drop_zone">ここにファイルをドロップ</div>
<output id="list"></output>

JavaScript


  function handleFileSelect(evt) {
    evt.stopPropagation();
    evt.preventDefault();

    var files = evt.dataTransfer.files; // FileList object.

    // Loop through the FileList and render image files as thumbnails.
    for (var i = 0, f; f = files[i]; i++) {

      // Only process image files.
      if (!f.type.match('image.*')) {
        continue;
      }

      var reader = new FileReader();

      // Closure to capture the file information.
      reader.onload = (function(theFile) {
        return function(e) {
          // Render thumbnail.
          var span = document.createElement('span');
          span.innerHTML = ['<img class="thumb" src="', e.target.result,
                            '" title="', escape(theFile.name), '"/>'].join('');
          document.getElementById('list').insertBefore(span, null);
        };
      })(f);

      // Read in the image file as a data URL.
      reader.readAsDataURL(f);
    }
  }

  function handleDragOver(evt) {
    evt.stopPropagation();
    evt.preventDefault();
    evt.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.
  }

  // Setup the dnd listeners.
  var dropZone = document.getElementById('drop_zone');
  dropZone.addEventListener('dragover', handleDragOver, false);
  dropZone.addEventListener('drop', handleFileSelect, false);

参考: http://www.html5rocks.com/ja/tutorials/file/dndfiles/


✒️️ Edit  ⏰ History  🗑 Delete