📝 BLOG.IK.AM

@making's memo
(🗃 Categories 🏷 Tags)

HTML5でファイルをドラッグ&ドロップするサンプル

🗃 {Programming/JavaScript/HTML5/File}

🏷 HTML5 🏷 JavaScript

🗓 Updated at 2014-04-10T17:11:09+09:00 by Toshiaki Maki  🗓 Created at 2014-04-10T17:11:09+09:00 by Toshiaki Maki  {✒️️ Edit  ⏰ History}


☠ Danger: This content is too old. You should avoid reading. If you want to read, please click .

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

CSS

#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.

    // files is a FileList of File objects. List some properties.
    var output = [];
    for (var i = 0, f; f = files[i]; i++) {
      output.push('<li><strong>', escape(f.name), '</strong> (', f.type || 'n/a', ') - ',
                  f.size, ' bytes, last modified: ',
                  f.lastModifiedDate.toLocaleDateString(), '</li>');
    }
    document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
  }

  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/