Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 Drag and Drop - detect folders in Safari (FileList, File)

I've set up a drag and drop file upload script in JS (AJAX POST) and I'm having difficulties filtering folders in Safari - Version 5.0.3 (6533.19.4).

Whenever I drop multiple files/folders into the browser, Chrome will filter out the folders, and Firefox will return 0 for .size so it's trivial to protect against those cases. Safari, however, will return a 68 byte file (the size of the folder).

Is there any way to test whether this File (item in FileList) is a folder? Can't seem to find anything in the File/Blob API that tests for this condition (no point in trying .type, since it returns nothing for unknown files as well as folders...)

A bit more info:

Basically what happens is that the AJAX request has an empty body. I'm uploading with FormData:

var file = ...; // the dropped file
var formData = new FormData();
formData.append("file", file);
var xhr = new XMLHttpRequest();
...
xhr.send(formData);
like image 595
biasedbit Avatar asked Feb 01 '11 00:02

biasedbit


1 Answers

We can read a file, with FileReader. Code can be like this:

Array.prototype.forEach.call(e.dataTransfer.files, function (file) {
  var reader = new FileReader();
  reader.onload = function (event) {
    // it's a file
    addFile(file);
  };
  reader.onerror = function (event) {
    alert("Uploading folders not supported in Safari");
  }
  reader.readAsDataURL(file);
});

For folders it will give error:

Failed to load resource: The operation couldn’t be completed. (WebKitBlobResource error 4.)
like image 162
Pavel Evstigneev Avatar answered Sep 22 '22 03:09

Pavel Evstigneev