A file object is an instance of Blob but a blob object is not an instance of File
new File([], 'foo.txt').constructor.name === 'File' //true
new File([], 'foo.txt') instanceof File // true
new File([], 'foo.txt') instanceof Blob // true
new Blob([]).constructor.name === 'Blob' //true
new Blob([]) instanceof Blob //true
new Blob([]) instanceof File // false
new File([], 'foo.txt').constructor.name === new Blob([]).constructor.name //false
If you must convert a file object to a blob object, you can create a new Blob object using the array buffer of the file. See the example below.
const file = new File(['hello', ' ', 'world'], 'hello_world.txt', {type: 'text/plain'});
//or const file = document.querySelector('input[type=file]').files[0];
const reader = new FileReader();
reader.onload = function(e) {
const blob = new Blob([new Uint8Array(e.target.result)], {type: file.type });
console.log(blob);
};
reader.readAsArrayBuffer(file);
As pointed out by @bgh you can also use the arrayBuffer method of the File object. See the example below.
const file = new File(['hello', ' ', 'world'], 'hello_world.txt', {type: 'text/plain'});
//or const file = document.querySelector('input[type=file]').files[0];
file.arrayBuffer().then((arrayBuffer) => {
const blob = new Blob([new Uint8Array(arrayBuffer)], {type: file.type });
console.log(blob);
});
If your environment supports async/await you can use a one-liner like below
const fileToBlob = async (file) => new Blob([new Uint8Array(await file.arrayBuffer())], {type: file.type });
console.log(await fileToBlob(new File(['hello', ' ', 'world'], 'hello_world.txt', {type: 'text/plain'})));
file instanceof Blob; // true
– Xavierxaviera