Last active
April 7, 2017 11:38
-
-
Save jirevwe/b0f481c18ccf357eb05a2d3a02f7313b to your computer and use it in GitHub Desktop.
DropzoneJS nodejs example code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//helper to get a file extension | |
String.prototype.getExtension = function() { | |
var basename = this.split(/[\\/]/).pop(), // extract file name from full path ... | |
// (supports `\\` and `/` separators) | |
pos = basename.lastIndexOf("."); // get last position of `.` | |
if (basename === "" || pos < 1) // if file name is empty or ... | |
return ""; // `.` not found (-1) or comes first (0) | |
return basename.slice(pos + 1); // extract extension ignoring `.` | |
}; | |
Array.prototype.indexOf || (Array.prototype.indexOf = function(d, e) { | |
var a; | |
if (null == this) throw new TypeError('"this" is null or not defined'); | |
var c = Object(this), | |
b = c.length >>> 0; | |
if (0 === b) return -1; | |
a = +e || 0; | |
Infinity === Math.abs(a) && (a = 0); | |
if (a >= b) return -1; | |
for (a = Math.max(0 <= a ? a : b - Math.abs(a), 0); a < b;) { | |
if (a in c && c[a] === d) return a; | |
a++ | |
} | |
return -1 | |
}); | |
let files = []; | |
Dropzone.options.uploadzone = { | |
url:'/upload', | |
addRemoveLinks: true, | |
paramName: 'attachment', | |
maxFilesize: 10, | |
maxFiles: 5, | |
dictDefaultMessage: 'Drag an file here to upload, or click to select', | |
acceptedFiles: '.png, .jpg, .jpeg, .gif, .pdf, .zip, .docx, .doc', | |
renameFilename: (name) => { | |
return mail_id + '-' + name; | |
}, | |
init: function() { | |
let myDropzone = this; | |
let xhr = undefined; | |
this.on('success', function(file, resp){ | |
files.push(resp); | |
}); | |
this.on('error', function (file, error, xhr){ | |
console.log(error); | |
}); | |
this.on('removedfile', function(file){ //delete the file | |
let file_index = files.find((n) => { return n.originalname == mail_id + '-' +file.name }); | |
xhr = $.ajax({ | |
url: "http://localhost:3000/uploads/delete", | |
type: "POST", | |
data: {file : file_index} | |
}); | |
files.splice(files.indexOf(file_index), 1); | |
}); | |
let fn = () => | |
{ | |
if(xhr != undefined && xhr.readyState != 4) | |
xhr.abort(); | |
}; | |
setInterval(fn, 500); | |
}, | |
accept: function(file, done) { | |
let ext = file.name.toString().getExtension(); | |
if( ext == 'pdf' || ext == 'png' || ext == 'png'|| ext == 'jpeg' || | |
ext == 'docx' || ext == 'doc' || ext == 'xlxs' || ext == 'jpg' | |
){ | |
done(); | |
} | |
else | |
done('Invalid file type'); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment