[javascript] How to instantiate a File object in JavaScript?

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

This question is related to javascript file-upload upload

The answer is


Now you can!

_x000D_
_x000D_
var parts = [_x000D_
  new Blob(['you construct a file...'], {type: 'text/plain'}),_x000D_
  ' Same way as you do with blob',_x000D_
  new Uint16Array([33])_x000D_
];_x000D_
_x000D_
// Construct a file_x000D_
var file = new File(parts, 'sample.txt', {_x000D_
    lastModified: new Date(0), // optional - default = now_x000D_
    type: "overide/mimetype" // optional - default = ''_x000D_
});_x000D_
_x000D_
var fr = new FileReader();_x000D_
_x000D_
fr.onload = function(evt){_x000D_
   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_x000D_
}_x000D_
_x000D_
fr.readAsText(file);
_x000D_
_x000D_
_x000D_


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.


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

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.


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


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to file-upload

bootstrap 4 file input doesn't show the file name How to post a file from a form with Axios File Upload In Angular? How to set the max size of upload file The request was rejected because no multipart boundary was found in springboot Send multipart/form-data files with angular using $http File upload from <input type="file"> How to upload files in asp.net core? REST API - file (ie images) processing - best practices Angular - POST uploaded file

Examples related to upload

Upload file to SFTP using PowerShell This application has no explicit mapping for /error Schedule automatic daily upload with FileZilla jQuery AJAX file upload PHP How to find when a web page was last updated Summernote image upload on change event for file input element Multiple files upload in Codeigniter How to upload files on server folder using jsp How do I measure request and response times at once using cURL?