198

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

1

6 Answers 6

267

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.

9
  • 2
    Produces Illegal constructor on Chrome 37 / Ubuntu so no it does not work Feb 12, 2015 at 19:09
  • 2
    This does work in Firefox 28+, Chrome 38+ and Opera 25+.However, Safari and IE still do not implement this constructor today (see caniuse.com/#feat=fileapi). I'm currently looking for a polyfill or a way to emulate this, but did'nt find any suitable solution so far. May 13, 2015 at 16:17
  • @PA.Buisson I'm not sure if this holds for all cases(it was sufficient for me), but you can use the Blob() constructor instead, as suggested here Jan 23, 2017 at 10:07
  • 2
    What is alternative of this for windows edge? Jul 24, 2017 at 9:43
  • 7
    For IE11, you can use the Blob class to construct a File object. This seems to be the most portable solution to me. file = new Blob([blobdata], {type: filetype, lastModified: filelastModified}); file.name = filename Apr 9, 2019 at 17:13
36

Now you can!

var parts = [
  new Blob(['you construct a file...'], {type: 'text/plain'}),
  ' Same way as you do with blob',
  new Uint16Array([33])
];

// Construct a file
var file = new File(parts, 'sample.txt', {
    lastModified: new Date(0), // optional - default = now
    type: "overide/mimetype" // optional - default = ''
});

var fr = new FileReader();

fr.onload = function(evt){
   document.body.innerHTML = evt.target.result + "<br><a href="+URL.createObjectURL(file)+" download=" + file.name + ">Download " + file.name + "</a><br>type: "+file.type+"<br>last modified: "+ file.lastModifiedDate
}

fr.readAsText(file);

6
19

Update

BlobBuilder has been obsoleted see how you go using it, if you're using it for testing purposes.

Otherwise apply the below with migration strategies of going to Blob, such as the answers to this question.

Use a Blob instead

As an alternative there is a Blob that you can use in place of File as it is what File interface derives from as per W3C spec:

interface File : Blob {
    readonly attribute DOMString name;
    readonly attribute Date lastModifiedDate;
};

The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system.

Create the Blob

Using the BlobBuilder like this on an existing JavaScript method that takes a File to upload via XMLHttpRequest and supplying a Blob to it works fine like this:

var BlobBuilder = window.MozBlobBuilder || window.WebKitBlobBuilder;
var bb = new BlobBuilder();

var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://jsfiddle.net/img/logo.png', true);

xhr.responseType = 'arraybuffer';

bb.append(this.response); // Note: not xhr.responseText

//at this point you have the equivalent of: new File()
var blob = bb.getBlob('image/png');

/* more setup code */
xhr.send(blob);

Extended example

The rest of the sample is up on jsFiddle in a more complete fashion but will not successfully upload as I can't expose the upload logic in a long term fashion.

4
  • 11
    This comment is out of date. Do not use BlobBuilder, use Blob constructor. Blob(['mythingy'], { type: "thingy" }) Jun 13, 2012 at 8:35
  • This code does not run. TypeError: BlobBuilder is not a constructor Jan 22, 2014 at 14:56
  • 2
    Unfortunately, BlobBuilder is obsolete: developer.mozilla.org/en-US/docs/Web/API/BlobBuilder
    – JD.
    Jul 17, 2014 at 19:31
  • DataTransferItemList.add requires File not Blob. So to the original question: How to instantiate File? Dec 2, 2014 at 14:29
4

Now it's possible and supported by all major browsers: https://developer.mozilla.org/en-US/docs/Web/API/File/File

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

The idea ...To create a File object (api) in javaScript for images already present in the DOM :

<img src="../img/Products/fijRKjhudDjiokDhg1524164151.jpg">

var file = new File(['fijRKjhudDjiokDhg1524164151'],
                     '../img/Products/fijRKjhudDjiokDhg1524164151.jpg', 
                     {type:'image/jpg'});

// created object file
console.log(file);

Don't do that ! ... (but I did it anyway)

-> the console give a result similar as an Object File :

File(0) {name: "fijRKjokDhgfsKtG1527053050.jpg", lastModified: 1527053530715, lastModifiedDate: Wed May 23 2018 07:32:10 GMT+0200 (Paris, Madrid (heure d’été)), webkitRelativePath: "", size: 0, …}
lastModified:1527053530715
lastModifiedDate:Wed May 23 2018 07:32:10 GMT+0200 (Paris, Madrid (heure d’été)) {}
name:"fijRKjokDhgfsKtG1527053050.jpg"
size:0
type:"image/jpg"
webkitRelativePath:""__proto__:File

But the size of the object is wrong ...

Why i need to do that ?

For example to retransmit an image form already uploaded, during a product update, along with additional images added during the update

-5

Because this is javascript and dynamic you could define your own class that matches the File interface and use that instead.

I had to do just that with dropzone.js because I wanted to simulate a file upload and it works on File objects.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.