Last active
October 3, 2020 16:27
-
-
Save LalanaChami/834e8a77720d93d3c23cce0b58f84c9a to your computer and use it in GitHub Desktop.
typescript mime type validator to a file picker in order pick png and jpg images
This file contains 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
import { AbstractControl } from '@angular/forms'; | |
import { Observable, Observer } from 'rxjs'; | |
export const mimeType =( | |
control: AbstractControl | |
): Promise<{[key: string]:any}> | Observable<{[key: string]:any}> =>{ | |
const file =control.value as File; | |
const fileReader = new FileReader(); | |
const frObs = Observable.create((observer : Observer<{[key: string]:any}>)=>{ | |
fileReader.addEventListener("loadend", ()=>{ | |
const arr = new Uint8Array(fileReader.result as ArrayBuffer).subarray(0,4); | |
let header = ""; | |
let isValid = false; | |
for(let i=0;i<arr.length; i++){ | |
header += arr[i].toString(16); | |
} | |
switch(header){ | |
case "89504e47": isValid=true; break; | |
case "ffd8ffe1": | |
case "ffd8ffe2": | |
case "ffd8ffe3": | |
case "ffd8ffe8": isValid=true; break; | |
default: isValid=false; break; | |
} | |
if(isValid){ | |
observer.next(null); | |
} | |
else{ | |
observer.next({invalidMimeType: true}); | |
} | |
observer.complete(); | |
}); | |
fileReader.readAsArrayBuffer(file); | |
}); | |
return frObs; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment