sajad torkamani

In a nutshell

The Blob object represents a “Binary Large Object” which is a file-like object of raw data. Blobs give you a way to handle and manipulate binary data (e.g., images, audio, or video) using JavaScript code.

For example, once you create or have a handle for a blob object, common use cases include:

  • File uploads: When a user selects a file from their file system using a web browser, the selected file is often represented as a Blob object. Your JavaScript code can send this blob object to an API endpoint for upload or further processing.
  • Image manipulation. You can create a blob from an existing image and then perform operations on it like resizing or cropping.
  • Audio or video playback. You can set a blob as the source of a video or audio player and stream the blob data progressively.
  • Downloads. Your API can return files as blobs and your JavaScript code can use APIs like URL.createObjectURL() to generate downloadable links from the blob.

Blobs can be read as text or binary data, or converted into a ReadableStream so that its methods can be used for processing the data.

Recipes

Create a blob

const response = await axiosService.post(
  `/api/download/${downloadToken}`,
   {},
   { responseType: 'blob' }
)

// This gives us a Blob object
const blob = new Blob([response.data], { type: 'application/pdf' })

Create URL for blob

You can use URL.createObjectURL() to create a URL to represent a Blob object (or also a File or MediaSource.

URL.createObjectUrl(yourBlobObject)

When you use URL.createObjectURL(), you’ll then want to call URL.revokeObjectURL() to tell the browser that it no longer needs to keep a reference to the old file. The browser automatically releases object URLs when the document is unloaded but it’s good practice to help browsers when you’re sure that you can explicitly unload them. This can help avoid memory leaks.

Sources

Tagged: Web APIs

Leave a comment

Your email address will not be published. Required fields are marked *