How to Convert Blob to File Using JavaScript
This tutorial instructs how to convert blob to file using JavaScript. The blob (Binary Large Object) is defined as a small chunk of binary data stored in database systems as a single entity.
The primary use of blobs is to hold images, videos, and other multimedia objects. Remember, not all database management systems support blobs.
Convert Blob to File Using JavaScript
A Blob()
is just like a File()
but with two differences, the lastModifiedDate
and the name
. The Blob()
does not have lastModifiedDate
and name
.
So, we have two options, either add these two properties to the blob or create an actual file’s instance. Let’s see both scenarios one by one.
Add lastModifiedDate
and name
property to blob.
function convertBlobToFile(blob, fileName) {
blob.lastModifiedDate = new Date();
blob.name = fileName;
return blob;
}
// Remember, the first parameter of Blob must be an array
var blob = new Blob(['This is the sample data'], {type: 'text/plain'});
// we are giving a url for an image as second parameter below
var file = convertBlobToFile(blob, 'https://bit.ly/3vsUaOe');
console.log(blob instanceof File); // returns false
console.log(blob);
Output:
false
[object Blob] {
arrayBuffer: function arrayBuffer() { [native code] },
lastModifiedDate: [object Date] { ... },
name: "https://bit.ly/3vsUaOe",
size: 23,
slice: function slice() { [native code] },
stream: function stream() { [native code] },
text: function text() { [native code] },
type: "text/plain"
}
Notice that the Blob
acts like a File
but not an instance of the File
. Let’s practice the same example by creating an instance of File
.
JavaScript Code:
// Remember, the first parameter of Blob must be an array
var blob = new Blob(['This is the sample data'], {type: 'text/plain'});
const file = new File([blob], 'https://bit.ly/3vsUaOe', {
type: blob.type,
});
console.log(file instanceof File); // returns true
console.log(file instanceof Blob); // returns true
console.log(file);
Output:
true
true
[object File] {
arrayBuffer: function arrayBuffer() { [native code] },
lastModified: 1646123706585,
lastModifiedDate: [object Date] { ... },
name: "https://bit.ly/3vsUaOe",
size: 23,
slice: function slice() { [native code] },
stream: function stream() { [native code] },
text: function text() { [native code] },
type: "text/plain",
webkitRelativePath: ""
}
Here, you may have noticed that the file
is an instance of File
and Blob
both because the file
is inheriting the properties of Blob
.