Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if variable holds File or Blob

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?

like image 668
alexandernst Avatar asked Jul 20 '15 20:07

alexandernst


People also ask

How can I tell if a file is a blob?

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.

How can I tell if an object is a file type?

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.


2 Answers

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 
like image 137
Nick Brunt Avatar answered Sep 28 '22 02:09

Nick Brunt


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'; 
like image 36
Reflective Avatar answered Sep 28 '22 02:09

Reflective