How to Create a Blob from a File in JavaScript?

Estimated read time 1 min read

A Blob (Binary Large Object) is a type of object in JavaScript that represents a file-like object of immutable, raw data. To create a Blob from a file in JavaScript, you can use the Blob constructor along with an array of data and an optional options object:

const file = new File(['Hello, World!'], 'hello.txt', { type: 'text/plain' });
const blob = new Blob([file], { type: 'text/plain' });

In this example, file is a File object that contains the string "Hello, World!" and is named "hello.txt". The blob is created from this file object and specifies a type of "text/plain".

You can then use the Blob with APIs that support Blobs, such as the URL.createObjectURL method to create a URL that can be used as the src attribute of an <a> element or an <img> element. For example:

const url = URL.createObjectURL(blob);
document.querySelector('a').href = url;

In this example, the URL.createObjectURL method creates a URL from the Blob, and the URL is assigned to the href attribute of an <a> element, allowing you to download the file by clicking on the link.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply