'Stop dropping folders in dropzone
I'm using dropzone.js and I want to prevent dropping folders because it drops the folders recursively that may lead to a frozen page if there are thousands of files in nested folders. How can I do that?
Let me explain in more detail. Here is how dropzone handles "drop" event:
{
key: "drop",
value: function drop(e) {
if (!e.dataTransfer) {
return;
}
this.emit("drop", e); // Convert the FileList to an Array
// This is necessary for IE11
var files = [];
for (var i = 0; i < e.dataTransfer.files.length; i++) {
files[i] = e.dataTransfer.files[i];
} // Even if it's a folder, files.length will contain the folders.
if (files.length) {
var items = e.dataTransfer.items;
if (items && items.length && items[0].webkitGetAsEntry != null) {
// The browser supports dropping of folders, so handle items instead of files
this._addFilesFromItems(items);
} else {
this.handleFiles(files);
}
}
this.emit("addedfiles", files);
}
I want to make a change to this to prevent dropping folders but I don't want to manipulate dropzone source code:
{
key: "drop",
value: function drop(e) {
if (!e.dataTransfer) {
return;
}
// ...
if (files.length) {
var items = e.dataTransfer.items;
if (items && items.length && items[0].webkitGetAsEntry != null) {
// Here is the change
var folder = items[0].webkitGetAsEntry().isDirectory;
if (folder) {
return;
}
this._addFilesFromItems(items);
} else {
this.handleFiles(files);
}
}
this.emit("addedfiles", files);
}
So, how can I override "drop" event?
Solution 1:[1]
I tried to solve the problem by removing dropzone's default "drop" event listener and adding my own listener.
BTW, I removed the event listener using DOM removeEventListener because dropzone adds the listeners with DOM addEventListener.
Solution 2:[2]
Just set the webkitdirectiory-attribute of the hidden file input to False. This will only allow (standalone) files to be uploaded.
$("div#dropzoneDiv").dropzone({
url: '/upload',
init: function() {
this.hiddenFileInput.setAttribute("webkitdirectory", false);
}
});
Solution 3:[3]
Add this:
accept: function(file, done) {
if (file.fullPath !== undefined && (file.fullPath.includes("/") || file.fullPath.includes("\\") )) {
done("Please, do not upload a whole directory, only files that are inside.");
return;
}
done();
},
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Shahram |
| Solution 2 | donschlonzo |
| Solution 3 | Eric |
