How to Instantiate a File Object in JavaScript

How to instantiate a File object in JavaScript?

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.

how to instantiate new file object javascript

This is what I ended up doing. Shows how to get the blob object as well as convert it to a file type.

function autoLoadGame(fileName) {
var gameLocation = '/Content/Roms/Snes/' + fileName;
var blob = null;
var xhr = new XMLHttpRequest();
xhr.open("GET", gameLocation, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == XMLHttpRequest.DONE) {
var blob = xhr.response;
var file = new File([blob], fileName, { type: '', lastModified: Date.now() });
snes_readfile(file);
}
}
xhr.responseType = "blob";
xhr.send();
}

how to create file object in js?

function urlToBlob(url){
return new Promise((resolve,reject)=>{
var xhr = new XMLHttpRequest();
xhr.open( "GET", url, true );
xhr.responseType = "blob";
xhr.onload = function( e ) {
resolve(this.response)
};
xhr.onerror = function( error ){
reject(error)
}
xhr.send();
})
}
let fileUrl = "https:XYZ/ABC/1/סריקה0252_28-05-2019_11:24:40.pdf"
urlToBlob(fileUrl).then(function(blob){
console.log(blob)
// you will get blob object of that file here
})

Here is the function to convert it. this will load the file first to the local. once it will be loaded, it will return blob object as return type is defined as a blob.

Create File object using file path

File API needs a Blob here is work-arround

var GetFileBlobUsingURL = function (url, convertBlob) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.responseType = "blob";
xhr.addEventListener('load', function() {
convertBlob(xhr.response);
});
xhr.send();
};

var blobToFile = function (blob, name) {
blob.lastModifiedDate = new Date();
blob.name = name;
return blob;
};

var GetFileObjectFromURL = function(filePathOrUrl, convertBlob) {
GetFileBlobUsingURL(filePathOrUrl, function (blob) {
convertBlob(blobToFile(blob, 'testFile.jpg'));
});
};
var FileURL="test/test.jpg"
GetFileObjectFromURL(FileURL, function (fileObject) {
console.log(fileObject);
});

How to create a file object with a path in NodeJS?

So, I search with File Systems and others possibilities and nothing.
I decide to create my own File object with JSON.

  var imagePath = path.join('/images/logo.png', 'logo.png');

if (fs.statSync(imagePath)) {
var bitmap = fs.readFileSync(imagePath);
var bufferImage = new Buffer(bitmap);

Magic = mmm.Magic;
var magic = new Magic(mmm.MAGIC_MIME_TYPE);
magic.detectFile(imagePath, function(err, result) {
if (err) throw err;
datas = [{"buffer": bufferImage, "mimetype": result, "originalname": path.basename(imagePath)}];
var JsonDatas= JSON.parse(JSON.stringify(datas));
log.notice(JsonDatas);
});
}

The output :

{ 
buffer:
{
type: 'Buffer',
data:
[
255,
216,
255
... 24908 more items,
[length]: 25008
]
},
mimetype: 'image/png',
originalname: 'logo.png'
}

I think is probably not the better solution, but it give me what I want. If you have a better solution, you are welcome.

How to instantiate a File object in Typescript?

The File class is not defined as part of the TypeScript language proper, but rather is a part of the DOM specification. TypeScript provides a standard declaration file for DOM objects as part of the stdlib, which you can view for yourself here:

/** The File interface provides information about files and allows JavaScript in a web page to access their content. */
interface File extends Blob {
readonly lastModified: number;
readonly name: string;
}

declare var File: {
prototype: File;
new(fileBits: BlobPart[], fileName: string, options?: FilePropertyBag): File;
};

Of course the declaration file itself isn't very user friendly. You'll probably find the MDN DOM API documentation more useful (though note, it's for JavaScript, not TypeScript, so don't expect any explicit type annotations). It provides this example:

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.



Related Topics



Leave a reply



Submit