How to convert Blob to File in JavaScript
This function converts a Blob
into a File
and it works great for me.
Vanilla JavaScript
function blobToFile(theBlob, fileName){
//A Blob() is almost a File() - it's just missing the two properties below which we will add
theBlob.lastModifiedDate = new Date();
theBlob.name = fileName;
return theBlob;
}
TypeScript (with proper typings)
public blobToFile = (theBlob: Blob, fileName:string): File => {
var b: any = theBlob;
//A Blob() is almost a File() - it's just missing the two properties below which we will add
b.lastModifiedDate = new Date();
b.name = fileName;
//Cast to a File() type
return <File>theBlob;
}
Usage
var myBlob = new Blob();
//do stuff here to give the blob some data...
var myFile = blobToFile(myBlob, "my-image.png");
You can use the File constructor:
var file = new File([myBlob], "name");
As per the w3 specification this will append the bytes that the blob contains to the bytes for the new File object, and create the file with the specified name http://www.w3.org/TR/FileAPI/#dfn-file
Joshua P Nixon's answer is correct but I had to set last modified date also. so here is the code.
var file = new File([blob], "file_name", {lastModified: 1534584790000});
1534584790000 is an unix timestamp for "GMT: Saturday, August 18, 2018 9:33:10 AM"