How to instantiate a File object in JavaScript?

julesbou picture julesbou · Dec 5, 2011 · Viewed 275.3k times · Source

There's a File object in JavaScript. I want to instantiate one for testing purposes.

I have tried new File(), but I get an "Illegal constructor" error.

Is it possible to create a File object ?


File Object reference : https://developer.mozilla.org/en/DOM/File

Answer

AlainD picture AlainD · Oct 3, 2014

According to the W3C File API specification, the File constructor requires 2 (or 3) parameters.

So to create a empty file do:

var f = new File([""], "filename");
  • The first argument is the data provided as an array of lines of text;
  • The second argument is the filename ;
  • The third argument looks like:

    var f = new File([""], "filename.txt", {type: "text/plain", lastModified: date})
    

It works in FireFox, Chrome and Opera, but not in Safari or IE/Edge.