I want to make sure that the file i am using is really a pdf and not another file with a pdf extension.
in my code, the file lives inside a file object called file. The parameter file.type show as a "application/pdf" regardless of what file it really is, if it has a .pdf extension, it will show this file type. so this is not a good enough check.
If i read the contents of the file using a filereader:
let reader = new FileReader();
reader.readAsBinaryString(file);
reader.onloadend = function() {
console.log(reader.result.includes("%PDF"))
}
then i can see on the console a true of false if it is really a pdf file. What am stuck with using this method is i can not get any usable data out of the function.
So is there away i can use the results of reader.onloadend = function() {} in the rest of my code or is there a better why to validate the file.
Many Thanks
EDIT: Thanks everyone on the validation of a PDF. I am pretty happy with this issue now. The problem i have is to get the contents of the file or the results of the validation in to a variable i can use. I am having problems with promises etc.
So i know have:
function readFile(file){
return new Promise((resolve, reject) => {
const fr = new FileReader();
fr.onload = () => {
if (fr.result.includes("PDF")){ // i will use the new pdf validation here!
resolve("OK");
} else {
reject("Error");
}
};
fr.onerror = reject;
fr.readAsBinaryString(file);
});
}
Then i call this with:
readFile(file).then(
function(value) {console.log(value);},
function(error) {console.log(error);}
);
but i still can not then get this data in to a variable i can use.
for example i would like something like this:
var state;
readFile(file).then(
function(value) {state = value;},
function(error) {state = error;}
);
if (state == "OK"){...
but 'state' is just showing as undefined.