Check if variable contains File or Blob

Javascript has both File

, and Blob

to represent files, and both of them are almost the same. Is there a way to check if a variable is datatyped File

or not Blob

?

+3


source to share


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


The 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

      

+6


source


Compare the constructor class:

var b = new Blob()
console.log(b.constructor === Blob) // true

      

+1


source


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







All Articles