Jun 8, 2010

Drag-and-Drop Files

I want to drag my desktop files into a Chrome app. I used the Drag-and-Drop feature in HTML5 to do this job.

Here is the DIV element. It's simple and the dragged files will be dropped here.
drop file here

Then, handle the drag-and-drop related events:
var dropZone = document.getElementById('drop-zone');

dropZone.addEventListener('dragenter', onDragEnter, false);
dropZone.addEventListener('dragover', onDragOver, false);
dropZone.addEventListener('dragleave', onDragLeave, false);
dropZone.addEventListener('drop', onDrop, false);
...

Now, let's implement the event handlers one by one (I've loaded jQuery first). First, while the files are being dragged enter the drop zone, I want to change the drop zone's style to highlight the DnD is firing. I added an ondrag style class to apply the highlight style:
var onDragEnter = function(event) {
  $(this).addClass('ondrag');

  event.stopPropagation();
  event.preventDefault();
};

In order to prevent the default DnD actions (e.g., open the files directly) by browser, it's necessary to call preventDefault and stopPropagation methods in these handlers:
var onDragOver = function(event) {
  event.stopPropagation();
  event.stopPropagation();
};

// Remove highlight style while the dragged files leave the drop zone.
var onDragLeave = function(event) {
  $(this).removeClass('ondrag');
  event.stopPropagation();
  event.stopPropagation();  
};

Finally, while the files are dropped, the drop event will be triggered.
var onDrop = function(event) {
  // remove the highlight style
  $(this).removeClass('ondrag');
  // get the file objects
  var files = event.dataTransfer.files;
  // process the file one-by-one
  for (var i = 0; i < files.length; ++i) {
    // File name: files[i].name
    // File size: files[i].size (in bytes)

    // To read files:
    // var fileReader = new FileReader();
    // fileReader.onload = function(event) { var content = event.target.result ...};
    // fileReader.readAsBinary(files[i]); or fileReader.readAsText(files[i], 'UTF-8') or fileReader.readAsDataURL(files[i]);
  }
};
You can also use FileReader to load the content of a file.

No comments:

Post a Comment