ngx-file-drop upload specific file type code example
Example: ngx-file-drop allow only image or pdf
public dropped(files: NgxFileDropEntry[]) {
if (files.length > 6) {
this.toastr.error("Cannot add more than 6 Files at a time.")
} else {
for (const droppedFile of files) {
if (droppedFile.fileEntry.isFile && this.isFileAllowed(droppedFile.fileEntry.name)) {
const fileEntry = droppedFile.fileEntry as FileSystemFileEntry;
fileEntry.file((file: File) => {
if (this.isFileSizeAllowed(file.size)) {
this.files.push(droppedFile);
if (this.files.length < 6) {
console.log(droppedFile.relativePath, file);
this.formData.append(`img${this.index}`, file, droppedFile.relativePath);
this.index++;
} else {
this.toastr.error("Maximum 6 files are allowed.");
}
} else {
this.toastr.error("Max size of a file allowed is 1mb, files with size more than 1mb are discarded.");
}
});
} else {
this.toastr.error("Only files in '.pdf', '.jpg', '.jpeg', '.png' format are accepted and directories are not allowed.");
}
}
}
}
isFileAllowed(fileName: string) {
let isFileAllowed = false;
const allowedFiles = ['.pdf', '.jpg', '.jpeg', '.png'];
const regex = /(?:\.([^.]+))?$/;
const extension = regex.exec(fileName);
if (undefined !== extension && null !== extension) {
for (const ext of allowedFiles) {
if (ext === extension[0]) {
isFileAllowed = true;
}
}
}
return isFileAllowed;
}
isFileSizeAllowed(size) {
let isFileSizeAllowed = false;
if (size < 1000000) {
isFileSizeAllowed = true;
}
return isFileSizeAllowed;
}