Skip to content
Tutorials Center
My learning

Topics

Lesson 99 of 156 · Browser APIs

Files, Blobs and Base64

Work with binary data in the browser - Blob and File objects, reading user-selected files, object URLs for previews, generating downloads and Base64 with btoa.

Sooner or later your web app has to deal with files: a profile photo the user picks, a CSV they want to import, a report they want to download, an image you generate on a canvas. Browsers handle all of these with a small family of objects. A Blob is a chunk of raw data with a type. A File is a Blob with a name and a date. Object URLs let you point an <img> or a link at a Blob, and Base64 turns binary data into plain text when you need to embed it in a string.

This lesson shows how the pieces fit together. You'll read files the user selects, preview images without uploading them, generate files for download and convert data to and from Base64. Everything happens inside the browser; no server is involved.

Blob: a chunk of data with a type

new Blob(parts, { type }) creates a Blob from a list of parts: strings, other Blobs, ArrayBuffers or typed arrays. The type is a MIME type such as "text/plain" or "image/svg+xml". A Blob is immutable: you can't change its contents, only create new Blobs from it.

JS Creating and reading a Blob

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A Blob has three ways to get its data back: text() (decoded as UTF-8), arrayBuffer() (raw bytes) and bytes() (a Uint8Array, newer), plus stream() for reading huge files piece by piece. All of them are asynchronous, because a Blob's data might live on disk rather than in memory.

File: a Blob with a name

A File is a Blob with two extra properties: name and lastModified (a timestamp). Every File is a Blob, so all the Blob methods work on it. You usually get File objects from the user, but you can create one yourself too:

JavaScript
const file = new File(["Hello!"], "greeting.txt", { type: "text/plain" });
file.name;          // "greeting.txt"
file.size;          // 6
file instanceof Blob; // true

Reading files the user selects

An <input type="file"> gives you access to files the user explicitly chooses, and nothing else. Its files property is a FileList (an array-like list of File objects). Add multiple to allow several files and accept to suggest types; see input types for the HTML side.

Inspecting and reading a chosen file

The file never leaves your computer: the page reads it locally. file.type comes from the file name's extension and may be empty or wrong, so treat it as a hint. If the type matters (for example, before processing an upload), check the content too, and always validate again on the server.

The same File objects arrive from drag and drop (event.dataTransfer.files in a drop handler, see Drag and Drop) and from pasting (event.clipboardData.files).

FileReader: the older API

Before Blobs had text() and arrayBuffer(), you read files with FileReader, an event-based API. You'll still see it in a lot of code, and it remains the simplest way to get a data URL:

JavaScript
const reader = new FileReader();
reader.addEventListener("load", () => {
  console.log(reader.result); // the file's contents
});
reader.addEventListener("error", () => console.error(reader.error));

reader.readAsText(file);        // result: a string
// reader.readAsDataURL(file);  // result: "data:image/png;base64,..."
// reader.readAsArrayBuffer(file);

In new code, prefer the promise-based await file.text() and await file.arrayBuffer().

Object URLs: pointing at a Blob

Many browser features expect a URL: <img src>, <a href>, <video src>, fetch(). URL.createObjectURL(blob) creates a temporary URL like blob:https://example.com/3f1c… that points at a Blob in memory. It's created instantly, no matter how big the file is, because no data is copied.

Image preview with an object URL

An object URL keeps its Blob alive in memory until you call URL.revokeObjectURL(url) or the page is closed. If you create URLs repeatedly, for example every time the user picks a new image, revoke the old ones, as the show() function does. Object URLs work only inside the page (and same-origin pages) that created them; you can't send one to a server or another user.

Object URLs and data URLs both produce something you can put in src. The difference: a data URL contains the whole file as Base64 text, which is about a third bigger and has to be built in memory, while an object URL is a short reference. For previews of user files, object URLs are the better choice.

Generating downloads

To let the user save data your page created, such as an export or a report, put it in a Blob, create an object URL and click a link that has the download attribute:

JavaScript
function downloadFile(content, fileName, type) {
  const blob = new Blob([content], { type });
  const url = URL.createObjectURL(blob);

  const link = document.createElement("a");
  link.href = url;
  link.download = fileName;   // the suggested file name
  link.click();               // no need to add it to the page

  // Give the browser a moment to start the download, then free the memory
  setTimeout(() => URL.revokeObjectURL(url), 1000);
}

const rows = [["name", "score"], ["Ana", 91], ["Ben", 78]];
const csv = rows.map((row) => row.join(",")).join("\n");
downloadFile(csv, "scores.csv", "text/csv");

Downloads are blocked in the editors. This site's sandboxed previews don't allow downloads, so the next example shows the generated file and its object URL instead of saving it. Paste downloadFile() into a page of your own to see the real download.

Building an export file

The CSV helper quotes values that contain commas, quotes or line breaks. The demo reads the file back through its object URL with fetch(); on a real page, you'd hand that URL to a download link as downloadFile() does.

Base64: binary data as text

Base64 encodes any bytes using only 64 safe characters (A–Z, a–z, 0–9, +, /, with = for padding). You'll meet it in data URLs, email attachments, JSON APIs that carry images, and tokens. It is an encoding, not encryption: anyone can decode it.

The browser has had two functions for this since the early days: btoa() ("binary to ASCII") encodes, and atob() decodes. Their catch is that they work on "binary strings", where each character must have a code below 256. Any other character throws:

JS btoa, atob and Unicode

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Typed arrays like Uint8Array and the TextEncoder/TextDecoder pair are the standard way to move between text and bytes.

The modern way: Uint8Array.toBase64()

Newer browsers add direct conversion methods to Uint8Array, which skip the "binary string" detour and support the URL-safe Base64 variant:

JavaScript
const bytes = new TextEncoder().encode("Grüße 👋");

bytes.toBase64();                          // "R3LDvMOfZSDwn5GL"
bytes.toBase64({ alphabet: "base64url" }); // uses - and _ instead of + and /
Uint8Array.fromBase64("R3LDvMOfZSDwn5GL"); // back to bytes
bytes.toHex();                             // "4772c3bc..."

These methods reached all major browser engines during 2025, so older browsers still lack them. Feature-detect with if (Uint8Array.prototype.toBase64) { ... } and fall back to the helper above.

Data URLs

A data URL embeds a whole file in a URL: data:<type>;base64,<data>. They're useful for small images in CSS or for sending a tiny file around as a string. You can build one with FileReader.readAsDataURL(), or by hand:

JavaScript
const svg = '<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><circle cx="5" cy="5" r="5"/></svg>';
const dataUrl = "data:image/svg+xml;base64," + btoa(svg);

For anything larger than a few kilobytes, a Blob with an object URL is faster and uses less memory.

Safety notes for files

  • Never trust a file's name or type. Users can rename virus.exe to cat.png. Check content on the server, and limit sizes on both sides (if (file.size > 5 * 1024 * 1024) …).
  • Don't insert file contents as HTML. A text or SVG file can contain <script> or event handlers. Show text with textContent, and show images through <img>, where SVG scripts don't run. The security lesson explains why.
  • Revoke object URLs you no longer need, especially for big files.

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. How is a File related to a Blob?

    File extends Blob, so every File supports Blob methods like text(), arrayBuffer() and slice().
  2. 2. Why should you call URL.revokeObjectURL() when you're done with an object URL?

    An object URL holds a reference to its Blob. Revoking it lets the memory be freed.
  3. 3. What happens with btoa("€5")?

    btoa() only accepts characters with codes 0–255. Encode text to UTF-8 bytes with TextEncoder first.
  4. 4. Which approach is best for previewing a large image the user just selected?

    An object URL is a short reference created instantly, without copying or growing the data by a third.
  5. 5. Is Base64 a safe way to hide a password in your front-end code?

    Base64 changes how data is written, not who can read it. It provides no secrecy at all.

Summary

  • A Blob is immutable binary data with a MIME type; read it with text(), arrayBuffer(), bytes() or stream(), and cut it with slice().
  • A File is a Blob with name and lastModified; you get them from file inputs, drag and drop and paste.
  • URL.createObjectURL() makes a temporary URL for previews and downloads; revoke it when done.
  • Downloads use an <a download> link pointing at an object URL.
  • Base64 turns bytes into text: btoa/atob need byte strings (use TextEncoder for Unicode), and Uint8Array.toBase64()/fromBase64() are the newer direct methods.

Next: Real-Time Data: WebSockets and Server-Sent Events.