Search code examples
javascriptfileapi

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?


Solution

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