Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to instantiate a File object in JavaScript?

People also ask

How do you instantiate a file object?

The call of the createNewFile() - Method writes the file to disk. Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist. You can simply check it by creating a File -object with a non existing file path and calling the File. exists() ; method.

How do you initialize a file in JavaScript?

We can create a file with the File constructor with JavaScript. For instance, we can write: const parts = [ new Blob(['you construct a file...'], { type: 'text/plain' }), ' Same way as you do with blob', new Uint16Array([33]) ]; const file = new File(parts, 'sample.

What is file object in JavaScript?

A File object is a specific kind of Blob , and can be used in any context that a Blob can. In particular, FileReader , URL. createObjectURL() , createImageBitmap() , and XMLHttpRequest. send() accept both Blob s and File s. See Using files from web applications for more information and examples.

How do I initialize a TypeScript file?

var file = new File(["foo"], "foo. txt", { type: "text/plain", }); And although this is technically JavaScript, it will compile just fine as TypeScript, and the inferred type of file will be File . @KarlAnthonyBaluyot as File doesn't actually instantiate anything; it's merely a type assertion.


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.


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

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.


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

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