Codectionary / Developer documentation / JavaScript

Binary Data with Blob and Object URLs

Blob represents immutable bytes with an optional MIME type. An object URL temporarily exposes a Blob to APIs that expect a URL. The URL is tied to a browser-managed resource; revoke it when the consumer no longer needs it, rather than treating it as permanent storage.

Syntax

const blob = new Blob(["Hello"], { type: "text/plain" });
const url = URL.createObjectURL(blob);
URL.revokeObjectURL(url);

Examples

Binary Data with Blob and Object URLs: working example

Run this standalone example in a modern browser console unless another environment is specified. Expected result: In a browser supporting Blob URLs, the console prints Hello Ada 10.

(async () => {
  const blob = new Blob(["Hello Ada\n"], { type: "text/plain;charset=utf-8" });
  const url = URL.createObjectURL(blob);
  try {
    const response = await fetch(url);
    console.log((await response.text()).trim(), blob.size);
  } finally {
    URL.revokeObjectURL(url);
  }
})();
  1. Expected result: In a browser supporting Blob URLs, the console prints Hello Ada 10.
  2. The Blob contains nine ASCII text characters plus a newline, totaling ten bytes.
  3. finally releases the URL after its asynchronous reader completes.

Best practices

  • Do not revoke an object URL before an image, download, or fetch has consumed it.
  • Store the underlying content when persistence is required.

Runtime & versions

Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

ECMAScript specification

Specifications & further reading