Check if variable contains File or Blob
4 answers
W3.org:
'The File object is a Blob object with a name attribute, which is a string;'
In the case of a file:
var d = new Date(2013, 12, 5, 16, 23, 45, 600);
var generatedFile = new File(["Rough Draft ...."], "Draft1.txt", {type: 'text/plain', lastModified: d});
console.log(typeof generatedFile.name == 'string'); // true
In case of Blob:
var blob = new Blob();
console.log(typeof blob.name); // undefined
Condition:
var isFile = typeof FileOrBlob.name == 'string';
+7
source to share
This works for me when trying to determine if an object is a file:
var reader = new FileReader();
if(file.type){
reader.readAsDataURL(file);
}
If I want to check if it is a specific file type, like an image, I do this:
if(file.type && file.type.indexOf('image') !== -1){
reader.readAsDataURL(file);
}
0
source to share