星期一, 2月 04, 2013

[jQuery] 上傳資料夾

目前Chrome瀏覽器在21版以後支援使用者上傳資料夾

多檔上傳
var dropzone = document.getElementById('dropzone');

dropzone.ondrop = function(e) {
  var length = e.dataTransfer.files.length;
  for (var i = 0; i < length; i++) {
    var file = e.dataTransfer.files[i];
    ... // do whatever you want
  }
};

上傳資料夾

dropzone.ondrop = function(e) {
  var length = e.dataTransfer.items.length;
  for (var i = 0; i < length; i++) {
    var entry = e.dataTransfer.items[i].webkitGetAsEntry();
    if (entry.isFile) {
      ... // do whatever you want
    } else if (entry.isDirectory) {
      ... // do whatever you want
    }
  }
};

Notice that a big difference here is that you can treat a dropped object as Entry (FileEntry or DirectoryEntry) by using new function called getAsEntry (webkitGetAsEntry).
After obtaining access to the Entry object, you can use standard file handling methods that were introduced in the FileSystem API specification. For example, this example shows how you can detect if a dropped object is a file or a directory by examining the .isFile(or the .isDirectory) field.



把結果印在console

Firefox

firefox目前不支援拖拉資料夾的function,拖拉資料夾會判斷成沒有type的檔案,可參考以下解法。只要檔案大小 % 4096就可以知道是否為資料夾

A file without an extension will also have a type of "". In fact, type cannot be relied on: Save a text file with a .jpg extension and load it into a file control, and its type will display as image/jpeg. And, a folder named "someFolder.jpg" will also have its type as image/jpeg.
Interestingly, in my experimentation, every folder I've looked at has had its File.size % 4096 as zero. However, of course, some files will have that as well.
The best you can do on the client side is guess and perhaps provide a user prompt asking whether it is a folder. Even your best guess can be wrong. In my quick experimentation, some files have an emptyFile.type, and a File.size % 4096 as zero. It does have a dot in it's file name, but that could easily be removed. Any extensionless file with a File.size % 4096 of zero could look like a folder, but actually be a legitimate file.
Handle it on the server to be sure. If handling it client side is important to you, provide a UI prompt to ask whether a file is a folder if it looks suspicious.

使用這個方法如果遇到無副檔名的空檔案就會判斷錯誤..XD

Safari (IE)

沒有留言:

張貼留言

留個話吧:)

其他你感興趣的文章

Related Posts with Thumbnails