Frontend Development 23 min read

Understanding Blob, File, Base64, URL.createObjectURL, ArrayBuffer, TypedArray, and DataView in Frontend Development

This article provides a comprehensive guide to the Blob and File objects, their methods such as slice, text, arrayBuffer, and stream, explains Base64 encoding, demonstrates how to use URL.createObjectURL for previews, and introduces ArrayBuffer, TypedArray, and DataView for low‑level binary data handling in web development.

Rare Earth Juejin Tech Community
Rare Earth Juejin Tech Community
Rare Earth Juejin Tech Community
Understanding Blob, File, Base64, URL.createObjectURL, ArrayBuffer, TypedArray, and DataView in Frontend Development

Introduction

In the journey of frontend development we constantly meet Blob, File, FileReader, ArrayBuffer, Base64, and URL.createObjectURL(). Instead of copying code snippets from search engines, this guide explains the underlying concepts so developers become "code masters" rather than "copy‑and‑paste" users.

Blob

The Blob object represents an immutable, raw data "file‑like" object. Its data can be read as text via the text() method or as binary via the arrayBuffer() method, and it can be converted to a readable stream with stream() . Blob enables efficient handling of large files or binary data without loading everything into memory, supporting operations such as slicing with slice() .

Blob can store any type of data – files, images, audio, video, or plain text.

The File interface extends Blob, adding file‑specific metadata from the user's system.

Basic Usage

You can create a Blob with the new Blob() constructor:

new Blob(blobParts)
new Blob(blobParts, options)

Parameters:

blobParts (optional): an iterable (e.g., an Array) containing ArrayBuffer, TypedArray, DataView, Blob, strings, or a mix of these.

options (optional): an object to set type (MIME type) and endings (line‑ending handling).

const blob1 = new Blob(["Hello, world!"], { type: "text/plain" });
const blob2 = new Blob(['
hey!
'], { type: "text/html" });

Key properties:

size : size of the Blob in bytes.

type : MIME type of the Blob.

Common methods:

slice([start], [end], [contentType]) – returns a new Blob containing a portion of the original data.

text() – returns a Promise that resolves to the Blob’s text content.

arrayBuffer() – returns a Promise that resolves to an ArrayBuffer of the Blob’s binary data.

stream() – returns a ReadableStream for streaming large blobs.

blob.text().then(text => console.log(text));
blob.arrayBuffer().then(buf => console.log(buf));
const readable = blob.stream();
const reader = readable.getReader();
reader.read().then(({done, value}) => {
  if (!done) console.log(new TextDecoder().decode(value));
});

Use Cases

Generate file downloads: create a Blob, generate a URL with URL.createObjectURL , and trigger a download.

Upload files: use a Blob or File with FormData for POST requests.

Image processing: read a Blob with FileReader to display or manipulate images.

const blob = new Blob(["This is a test file."], { type: "text/plain" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = "test.txt";
a.click();
URL.revokeObjectURL(url);

const formData = new FormData();
formData.append("file", blob, "example.txt");
fetch("/upload", { method: "POST", body: formData });

File

Basic Usage

The File object represents a file on the user's system. It inherits all Blob methods and adds metadata such as name , size , type , and lastModified .

Files can be obtained via:

File input element ( <input type="file"> ).

Drag‑and‑drop DataTransfer objects.

Programmatic construction with new File() .

<input type="file" id="fileInput" />

APIs Supporting Blob and File

FileReader

URL.createObjectURL()

Window.createImageBitmap() / WorkerGlobalScope.createImageBitmap()

fetch() body option

XMLHttpRequest.send()

FileReader

FileReader can only access files explicitly selected by the user (e.g., via an <input type="file"> element or drag‑and‑drop).

Properties

Property

Type

Description

readyState

Number

0 = EMPTY, 1 = LOADING, 2 = DONE.

result

Any

Contains the file content after a successful read.

error

DOMException

Describes any error that occurred during reading.

Methods

Method

Description

readAsArrayBuffer()

Read the Blob/File as an

ArrayBuffer

.

readAsBinaryString()

Read as a binary string.

readAsDataURL()

Read as a Base64‑encoded data URL.

readAsText()

Read as a text string (UTF‑8 by default).

abort()

Cancel the read operation.

Events

Event

Description

onloadstart

Fired when reading begins.

onprogress

Fired periodically as data is read.

onload

Fired when reading completes successfully.

onabort

Fired when reading is aborted.

onerror

Fired when an error occurs.

onloadend

Fired when the read operation finishes (success or failure).

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>FileReader Example</title>
  </head>
  <body>
    <input type="file" id="fileInput" accept=".txt">
    <div id="fileContent"></div>
    <script>
      const input = document.getElementById('fileInput');
      const output = document.getElementById('fileContent');
      input.addEventListener('change', e => {
        const file = e.target.files[0];
        if (!file) return;
        const reader = new FileReader();
        reader.onload = ev => output.textContent = ev.target.result;
        reader.onerror = ev => console.error('Error:', ev.target.error);
        reader.readAsText(file);
      });
    </script>
  </body>
</html>

Base64

Terminology

Base64 is an encoding method that converts binary data into an ASCII string, useful for transmitting binary data via text‑based protocols (e.g., URLs, JSON, email).

Encoding Principle

Base64 uses a 64‑character alphabet (A‑Z, a‑z, 0‑9, +, /).

Input bytes are grouped into 24‑bit blocks (3 bytes) and split into four 6‑bit values.

If the final block is less than 3 bytes, one or two = padding characters are added.

Example

Encoding the string "Hello" yields "SGVsbG8=".

Applications

Embedding images directly in HTML/CSS.

Transmitting binary data in JSON or XML.

Encoding email attachments.

URL.createObjectURL()

Basic Usage

The static method URL.createObjectURL() generates a temporary URL that references a File , Blob , or (deprecated) MediaSource . The URL is tied to the document’s lifecycle and should be released with URL.revokeObjectURL() when no longer needed.

Use Cases

Previewing uploaded files (images, video, audio).

Dynamically generating content without persisting it on the server.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Image Preview</title>
  </head>
  <body>
    <input type="file" id="fileInput" accept="image/*">
    <img id="preview" style="max-width:100%;display:none;">
    <script>
      document.getElementById('fileInput').addEventListener('change', e => {
        const file = e.target.files[0];
        if (!file) return;
        const url = URL.createObjectURL(file);
        const img = document.getElementById('preview');
        img.src = url;
        img.style.display = 'block';
        img.onload = () => URL.revokeObjectURL(url);
      });
    </script>
  </body>
</html>

ArrayBuffer, TypedArray, DataView

Basic Usage

ArrayBuffer is a fixed‑length raw binary data container. It cannot be accessed directly; instead, you create views such as TypedArray or DataView to read/write the data.

// Create an 8‑byte buffer
const buffer = new ArrayBuffer(8);
console.log(buffer.byteLength); // 8

TypedArray provides array‑like access to an ArrayBuffer for a specific numeric type (e.g., Int8Array , Uint32Array , Float64Array ).

let int8 = new Int8Array(4);
int8[0] = 1; int8[1] = 2;
let buffer = new ArrayBuffer(8);
let int32View = new Int32Array(buffer, 0, 2);
int32View[0] = 12345; int32View[1] = 67890;
console.log(int32View[0], int32View[1]);

DataView offers a flexible way to read/write multiple data types at arbitrary offsets, useful when the same buffer stores mixed types.

const buffer = new ArrayBuffer(8);
const view = new DataView(buffer);
view.setInt32(0, 12345, true); // little‑endian
view.setFloat32(4, 3.14159, true);
console.log(view.getInt32(0, true)); // 12345
console.log(view.getFloat32(4, true)); // 3.14159

Complete Example

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Binary Data Handling</title>
  </head>
  <body>
    <button id="writeData">Write Data</button>
    <pre id="output"></pre>
    <script>
      document.getElementById('writeData').addEventListener('click', () => {
        const buffer = new ArrayBuffer(16);
        const view = new DataView(buffer);
        view.setInt32(0, 12345, true);
        view.setFloat32(4, 3.14159, true);
        view.setUint8(8, 255);
        view.setInt16(9, 1234, true);
        const int32 = new Int32Array(buffer, 0, 2);
        const float32 = new Float32Array(buffer, 4, 1);
        const uint8 = new Uint8Array(buffer, 8, 2);
        const int16 = new Int16Array(buffer, 8, 1);
        const output = `Int32: ${int32[0]}, ${int32[1]}
Float32: ${float32[0]}
Uint8: ${uint8[0]}, ${uint8[1]}
Int16: ${int16[0]}`;
        document.getElementById('output').textContent = output;
      });
    </script>
  </body>
</html>

Conclusion

Blob and File are the primary objects for handling various file types in the browser. Under the hood they store binary data, which can be manipulated with ArrayBuffer, TypedArray, and DataView. Base64 converts binary data to a text representation, while URL.createObjectURL provides temporary URLs for previewing or streaming content without server round‑trips.

frontendArrayBufferblobDataViewTypedArrayBase64file()
Rare Earth Juejin Tech Community
Written by

Rare Earth Juejin Tech Community

Juejin, a tech community that helps developers grow.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.