ファイルを操作する

ファイル操作の応用例:ドラッグアンドドロップされたファイルをローカルファイルシステムに複製する
ブラウザのコンソールを開いた状態から、以下のエリアにファイルをドラッグアンドドロップして動作を確認してください

※Chromeからローカル環境のファイルを開き、コンソールから確認する場合、 "--allow-file-access-from-files" オプション付きのChromeを実行する必要があります。

drop here

このページに埋め込まれているコード

<div id="dropzone">drop here</div>
<script>
var dropzone = document.getElementById('dropzone');

dropzone.addEventListener('dragover', function() {
  event.preventDefault();
}, false);

dropzone.addEventListener('drop', function(event) {
  event.preventDefault();
  Array.prototype.forEach.call(event.dataTransfer.files, function(file) {
    copy(file, function(error, fileEntry) {
      if (error) return console.log(error);
      console.log('completed');
    });
  });
}, false);

function copy(file, callback) {
  window.webkitRequestFileSystem(TEMPORARY, 1024*1024, function(fs) {
    fs.root.getFile(file.name, { create: true, exclusive: true }, function(fileEntry) {
      fileEntry.createWriter(function(fileWriter) {
        fileWriter.onwriteend = function() {
          callback(null, fileEntry);
        };

        fileWriter.onerror = function(error) {
          callback(error, null);
        };

        fileWriter.write(file);
      },
      function(error) {
        callback(error, null);
      });
    },
    function(error) {
      callback(error, null);
    });
 });
}
</script>