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?
To check if a variable is a blob in JavaScript, we can use the instanceof operator. to create a blob with: const myBlob = new Blob(['test text'], { type: 'text/plain' }); We use the Blob constructor with the content for the blob as the first argument.
The function is f. isFile(). This function returns a boolean value of either true or false. If the object is a file in the directory, it returns true.
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
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';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With