angular drop file upload code example
Example: ngx-file-drop allow only image or pdf
//trick for max file size and file type check in ngx-file-drop
public dropped(files: NgxFileDropEntry[]) {
if (files.length > 6) {
this.toastr.error("Cannot add more than 6 Files at a time.")
} else {
// this.files = files;
for (const droppedFile of files) {
// Is it a file?
if (droppedFile.fileEntry.isFile && this.isFileAllowed(droppedFile.fileEntry.name)) {
const fileEntry = droppedFile.fileEntry as FileSystemFileEntry;
fileEntry.file((file: File) => {
if (this.isFileSizeAllowed(file.size)) {
//files array is used to display
//the files to the user which will be uploaded
this.files.push(droppedFile);
if (this.files.length < 6) {
// Here you can access the real file
console.log(droppedFile.relativePath, file);
this.formData.append(`img${this.index}`, file, droppedFile.relativePath);
this.index++;
/**
// You could upload it like this:
const formData = new FormData()
formData.append('logo', file, relativePath)
// Headers
const headers = new HttpHeaders({
'security-token': 'mytoken'
})
this.http.post('https://mybackend.com/api/upload/sanitize-and-save-logo', formData, { headers: headers, responseType: 'blob' })
.subscribe(data => {
// Sanitized logo returned from backend
})
**/
} 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 {
// It was a directory (empty directories are added, otherwise only files)
this.toastr.error("Only files in '.pdf', '.jpg', '.jpeg', '.png' format are accepted and directories are not allowed.");
// const fileEntry = droppedFile.fileEntry as FileSystemDirectoryEntry;
// console.log(droppedFile.relativePath, fileEntry);
}
}
}
}
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;
}