alexandernst
alexandernst

Reputation: 15089

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?

Upvotes: 59

Views: 87224

Answers (6)

Ignacio Bustos
Ignacio Bustos

Reputation: 1504

One liner solution to make life easier.

Based on Ric Flair

const isFile = input => 'File' in window && input instanceof File;
const isBlob = input => 'Blob' in window && input instanceof Blob;

const a = new File([1,2,3], "foo.txt", {type: "text/plain"});
...

console.log(isFile(a)) // true
...

Upvotes: 14

Ric Flair
Ric Flair

Reputation: 415

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.

Upvotes: 8

Nick Brunt
Nick Brunt

Reputation: 10067

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

Upvotes: 122

Marcos Kubis
Marcos Kubis

Reputation: 519

Compare the constructor class:

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

Upvotes: 5

Peter Drinnan
Peter Drinnan

Reputation: 4533

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);
}

Upvotes: 3

Reflective
Reflective

Reputation: 3917

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';

Upvotes: 25

Related Questions