JavaScript Blob: Create, Read, and Share Browser Data

Creating a Blob in JavaScript and reading Blob data with JavaScript, including object URL cleanup.

Create a Blob in JavaScript with new Blob(parts, options) when you need a file-like object containing immutable data. The parts can include strings and binary data; an optional MIME type describes the content. A browser can read a JavaScript-created Blob as text or use an object URL to offer it through a link.

The URL has its own lifetime. Keep it while the link or preview is usable, then revoke it when that interface is removed or replaced. This releases the browser’s URL reference without changing the original data.

Blob JavaScript Examples: Start With Data

A JavaScript Blob can combine several parts in order. Run this example in a browser console:

const blob = new Blob(["Hello, ", "browser!\n"], {
  type: "text/plain;charset=utf-8"
});

console.log(blob.size); // 16 bytes
console.log(blob.type); // "text/plain;charset=utf-8"

The constructor joins the parts into one sequence of bytes. size reports bytes, not the number of visible characters. This example uses ASCII characters, including a newline, so its byte count happens to match the character count. A character such as é takes two bytes when encoded as UTF-8, which makes that shortcut unreliable for general text.

For a Blob, JavaScript accepts a type option that labels the resulting data. The type can help a browser or another consumer interpret a resource, but setting it does not validate or convert the contents. Calling arbitrary bytes image/png does not turn them into a valid PNG image. If no type is supplied, the type property is an empty string.

Read the contents as text

To read a Blob, JavaScript provides the asynchronous text() method. It returns a promise that resolves to a UTF-8-decoded string:

async function showText() {
  const message = new Blob(["First line\n", "Second line"], {
    type: "text/plain;charset=utf-8"
  });
  const text = await message.text();
  console.log(text);
}

showText().catch(console.error);

The await belongs inside an async function in this example, so it can be pasted into a normal browser console without depending on top-level await. Catching the rejected promise gives the application a place to report a read error. The Blob text documentation explains the method and its UTF-8 decoding.

A Blob created in JavaScript is useful for generated text, but it can also contain binary data. For bytes rather than a decoded string, arrayBuffer() returns an ArrayBuffer asynchronously. Choose a reader that matches the data; decoding an arbitrary image as text will not produce a meaningful image representation.

When reading a Blob in JavaScript, consider the amount of data as well as its format. text() produces a complete string, which is convenient for a small generated report but may require substantial memory for a large file. A Blob in browser JavaScript also exposes stream() for processing data progressively; the consumer must still handle decoding and errors appropriately.

Take a slice without changing the original

A JavaScript Blob is immutable: its stored bytes are not edited in place. Use slice(start, end, type) to create another Blob containing a range, with an inclusive start and an exclusive end. The original remains available.

async function showSlice() {
  const source = new Blob(["abcdef"], { type: "text/plain" });
  const part = source.slice(1, 4, "text/plain");
  console.log(await part.text());   // "bcd"
  console.log(await source.text()); // "abcdef"
}

showSlice().catch(console.error);

The positions are byte offsets. They happen to line up with letters in this ASCII example, but a cut through a multibyte UTF-8 character may leave an incomplete sequence. Also pass a type for the new part when its consumer needs one: the slice’s type is empty by default. See MDN’s slice reference for the range behavior.

When changing data held in a JavaScript Blob, build a new object from the desired pieces. For example, put a header, the original Blob, and a footer in a new parts array. That construction creates a new value; it does not modify the source. Keeping both references lets you compare or reuse the original.

Create and release an object URL

An object URL gives a page a URL-shaped reference to a Blob. The following example creates a download link and keeps it active until the user removes it. Place this HTML and script in a page:

<button id="make" type="button">Create link</button>
<button id="remove" type="button">Remove link</button>
<div id="links"></div>
<script>
  const links = document.getElementById("links");
  let currentURL = null;

  function clearLink() {
    links.replaceChildren();
    if (currentURL !== null) {
      URL.revokeObjectURL(currentURL);
      currentURL = null;
    }
  }

  document.getElementById("make").addEventListener("click", () => {
    clearLink();
    const data = new Blob(["A local report\n"], { type: "text/plain" });
    currentURL = URL.createObjectURL(data);
    const link = document.createElement("a");
    link.href = currentURL;
    link.download = "report.txt";
    link.textContent = "Download report";
    links.append(link);
  });
  document.getElementById("remove").addEventListener("click", clearLink);
</script>

The browser’s JavaScript Blob URL stays usable while the link remains in the page. Clicking “Create link” again first removes the old link and revokes its URL, then creates a fresh one. Clicking “Remove link” does the same cleanup without replacing it. The download attribute suggests a filename; the browser controls the final download behavior.

Do not revoke immediately after creating a link or as soon as a preview loads if people still need to open, save, or otherwise use it. Revoke when the corresponding interface is no longer needed. Each call to createObjectURL() creates a separate URL to release. Browsers release document-created object URLs when the document unloads, but explicit cleanup matters in a long-lived page; see MDN’s blob URL guidance.

A Blob URL in JavaScript is a browser-managed reference, not a permanent address to store in a database or send to another user. If the document is closed or the URL is revoked, the link cannot serve as a durable way to retrieve the data. To share it later, store or upload the underlying bytes through an appropriate application workflow. For a preview created from a Blob using JavaScript, remove the preview first and then release its URL when the user is finished with it.

Blob or File?

A File is a specialized Blob with file-oriented metadata, including name and lastModified. A file selected through an <input type="file"> can be read with Blob methods as well as identified by its filename. Use a plain Blob for generated bytes when no name or modification timestamp is needed; use a File when that metadata is part of the task.

For browser JavaScript, a Blob and a File both represent immutable data. Neither is a promise that the declared MIME type matches the bytes, so validate uploaded content on the server according to the application’s requirements. A filename or type supplied by a client is information to inspect, not proof of format.

Before finishing, check that each object URL created for a Blob in JavaScript has an owner and a cleanup point. Keep the URL alive while a user can still use its link or preview; revoke it when that interface is removed or replaced. Choose File when you need file metadata, and Blob when the data and its type are enough.