Javascript has both File
and Blob
for file representation, and both are almost the same thing. Is there a way to check if a variable is holding a File
or a Blob
type of data?
W3.org:
'A File object is a Blob object with a name attribute, which is a string;'
In case of 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';
Easiest way:
a = new File([1,2,3], "file.txt");
b = new Blob([1,2,3]);
c = "something else entirely";
a instanceof File
> true
b instanceof File
> false
c instanceof File
> false
This works for me when trying to determine is 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);
}
Compare the constructor class:
var b = new Blob()
console.log(b.constructor === Blob) // true
Based on Nick Brunt's:
function isFile(input) {
if ('File' in window && input instanceof File)
return true;
else return false;
}
function isBlob(input) {
if ('Blob' in window && input instanceof Blob)
return true;
else return false;
}
//Test
const a = new File([1,2,3], "foo.txt", {type: "text/plain"});
const b = new Blob([1,2,3]);
const c = "something else entirely";
console.log(isFile(a)); //true
console.log(isBlob(a)); //true
console.log(isFile(b)); //false
console.log(isBlob(b)); //true
console.log(isFile(c)); //false
console.log(isBlob(c)); //false
Won't work for Opera mini as well as IE. Though with IE it won't matter because you may only use file input tags, in that case you'll definitely know it's a file.
if(x.name) ...
for quacks,if(x.constructor===File)
for pedantics. – dandavis Jul 20 '15 at 20:28x.constructor.name == 'Blob'
– Reflective Jul 20 '15 at 20:53