JavaScript Blob

JavaScript Blob

JavaScript Blob

A Blob (Binary Large Object) in JavaScript is used to represent raw binary data. It allows you to handle files or binary data in web applications, such as when you're working with images, audio files, videos, or other types of data that are not necessarily in text form.

A Blob can contain any kind of data, and it is most commonly used for:

  • Creating downloadable files
  • Handling file uploads
  • Working with binary data in APIs (e.g., Web APIs like FileReader or Canvas)

1️⃣ Creating a Blob

A Blob can be created using the Blob() constructor, which takes an array of data (such as strings, arrays, or other blobs) and an optional object specifying MIME types.

const data = ['Hello, world!']; const blob = new Blob(data, { type: 'text/plain' }); console.log(blob); // Blob { size: 13, type: "text/plain" }

In this example:

  • We create a Blob containing the string "Hello, world!" and specify the MIME type as text/plain.

2️⃣ Blob Constructor Syntax

let blob = new Blob(arrayOfData, options);
  • arrayOfData: An array of data to store in the Blob. The data can be strings, arrays, or other Blobs.
  • options (optional): An object that can include the following properties:
    • type: A string that specifies the MIME type of the Blob. For example, 'text/plain', 'image/png', 'application/json', etc.
    • endings: A string that can be 'native' or 'transparent', which controls how newlines are handled in text files. The default is 'native'.

3️⃣ Working with Blob

Once you have a Blob, you can use it in different ways, such as creating downloadable links, working with files, and reading data from it.

3.1 Creating a Downloadable File Link

You can create a download link for a Blob, allowing users to download data as a file.

const data = ['This is a test file.']; const blob = new Blob(data, { type: 'text/plain' }); const link = document.createElement('a'); link.href = URL.createObjectURL(blob); // Create a URL for the Blob link.download = 'test.txt'; // Specify the file name link.textContent = 'Download the file'; document.body.appendChild(link); // Append the link to the page

Here:

  • URL.createObjectURL(blob) creates a temporary URL for the Blob.
  • The user can click on the link to download the file as test.txt.

3.2 Reading Data from Blob

You can use the FileReader API to read the contents of a Blob, often useful for handling file uploads or image previews.

const blob = new Blob(['Hello, this is some text'], { type: 'text/plain' }); const reader = new FileReader(); reader.onload = function(event) { console.log(event.target.result); // Output: Hello, this is some text }; reader.readAsText(blob); // Read the Blob as text

In this case, the FileReader.readAsText() method reads the Blob’s content and outputs it as a string.

3.3 Using Blob with FormData for Uploads

You can append a Blob to a FormData object, which is often used in handling file uploads.

const formData = new FormData(); const blob = new Blob(['This is the content of the file'], { type: 'text/plain' }); formData.append('file', blob, 'test.txt'); // Append the Blob as a file // Example of sending the FormData using Fetch API fetch('/upload', { method: 'POST', body: formData }).then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error));

Here:

  • A Blob is appended to FormData as if it were a file.
  • This FormData can be sent via an AJAX request (e.g., using the fetch API).

4️⃣ Using Blob with Canvas

A Blob is often used when dealing with images or other media in web applications. You can create a Blob from the contents of a <canvas> element, for example:

const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); canvas.width = 100; canvas.height = 100; ctx.fillStyle = 'red'; ctx.fillRect(10, 10, 80, 80); // Convert canvas to Blob (image/png type) canvas.toBlob(function(blob) { console.log(blob); // Blob { size: 1024, type: "image/png" } }, 'image/png');

In this case:

  • The canvas is drawn with a red rectangle.
  • canvas.toBlob() creates a Blob from the canvas content in the specified MIME type (e.g., 'image/png').

5️⃣ Properties of Blob

  • size: The size (in bytes) of the Blob.
  • type: The MIME type of the Blob, which can be any valid MIME type (e.g., 'text/plain', 'application/json', 'image/jpeg').
const blob = new Blob(['Hello World'], { type: 'text/plain' }); console.log(blob.size); // Output: 11 console.log(blob.type); // Output: text/plain

6️⃣ Blob Methods

There are several methods you can use with a Blob to manipulate or interact with its data.

6.1 slice()

The slice() method is used to create a new Blob object that contains a portion of the original Blob.

const blob = new Blob(['Hello World!'], { type: 'text/plain' }); const slicedBlob = blob.slice(0, 5); // Slice from position 0 to 5 (Hello) const reader = new FileReader(); reader.onload = function(event) { console.log(event.target.result); // Output: Hello }; reader.readAsText(slicedBlob);

6.2 stream()

In newer environments (e.g., modern browsers), Blobs can be converted into a readable stream using stream(). This can be useful for streaming large files.

const blob = new Blob(['Streaming data example'], { type: 'text/plain' }); const stream = blob.stream(); stream.getReader().read().then(({ value, done }) => { console.log(value); // Output: Uint8Array });

7️⃣ Use Cases for Blob

  • Uploading files: You can create a Blob from an image, video, or other file input, and upload it using the FormData API.
  • Creating downloadable files: Blobs are useful for generating downloadable files in the browser (e.g., generating reports, images, text files, etc.).
  • Working with large data: Blobs can handle large binary data that cannot be efficiently handled with strings, such as media files, PDFs, etc.

8️⃣ Conclusion

A Blob is an essential object in JavaScript for dealing with binary data. It allows you to manage files, generate downloadable content, and interact with data that is not necessarily text-based. By using methods like toBlob(), slice(), and URL.createObjectURL(), you can work with files and binary data in a variety of ways.

Let me know if you need more details or examples! 😊

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close