To convert a File or Blob into a Base64 string in browser JavaScript, use FileReader.prototype.readAsDataURL(file) (or read a Blob via arrayBuffer() and encode bytes cleanly); to convert an image URL into a Base64 string, fetch the resource with fetch(url) to get a Blob and then convert that Blob to a data URL or Base64 string. A readAsDataURL() result looks like "data:image/png;base64,iVBORw0..." (a data URL), so split on "," when you need only the raw Base64 payload without the "data:image/...;base64," prefix, and ensure the remote image server allows cross-origin requests (CORS) when fetching URLs.
1. Converting a File or Blob to Base64 with FileReader
Wrap FileReader.readAsDataURL() in a Promise so you can await the result cleanly, while validating the File/Blob input and optionally stripping the "data:...;base64," prefix:
// Convert a File or Blob into a data URL ("data:image/...;base64,...") or raw Base64 string
function blobOrFileToBase64(fileOrBlob, { includePrefix = true } = {}) {
if (!(fileOrBlob instanceof Blob)) {
return Promise.reject(new TypeError("Expected a File or Blob instance."));
}
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => {
const result = typeof reader.result === "string" ? reader.result : "";
if (!result) {
reject(new Error("FileReader returned an empty result."));
return;
}
if (includePrefix) {
resolve(result);
return;
}
const commaIndex = result.indexOf(",");
resolve(commaIndex >= 0 ? result.slice(commaIndex + 1) : result);
};
reader.onerror = () => {
reject(reader.error ?? new Error("Failed to read file as Data URL."));
};
reader.readAsDataURL(fileOrBlob);
});
}
// Example usage (with an <input type="file" accept="image/*">):
// async function handleImageInputChange(event) {
// const file = event.target?.files?.[0];
// if (!file) return;
//
// const dataUrl = await blobOrFileToBase64(file, { includePrefix: true });
// const rawBase64 = await blobOrFileToBase64(file, { includePrefix: false });
// console.log({ dataUrlPrefix: dataUrl.slice(0, 30), rawLength: rawBase64.length });
// }
includePrefix: truevs.false: Keep the full data URL (data:image/png;base64,...) for<img src="...">or CSSurl(...), and strip the prefix (includePrefix: false) when an API expects raw Base64 bytes alone.- File size awareness: Base64 encoding expands binary data by roughly 33%, so check file size before reading large images into memory.
2. Converting an Image URL to Base64 via fetch() and Blob
To convert an image URL into a Base64 string, fetch the URL with fetch(), check response.ok, read .blob(), and convert that Blob using the same Base64 helper:
// Fetch an image URL and convert it to a data URL or raw Base64 string
async function imageUrlToBase64(url, { includePrefix = true, fetchOptions = {} } = {}) {
if (typeof url !== "string" || url.trim().length === 0) {
throw new TypeError("Expected url to be a non-empty string.");
}
const response = await fetch(url, fetchOptions);
if (!response.ok) {
throw new Error(`Failed to fetch image: HTTP ${response.status}`);
}
const blob = await response.blob();
if (!blob.type.startsWith("image/") && blob.size === 0) {
throw new Error("Fetched resource is not a valid image blob.");
}
return blobOrFileToBase64(blob, { includePrefix });
}
// Example usage (in a browser):
// imageUrlToBase64("https://example.com/avatar.png", { includePrefix: true })
// .then((base64Url) => console.log(base64Url.slice(0, 40)))
// .catch((err) => console.error(err));
- CORS requirement: Cross-origin image URLs must send appropriate
Access-Control-Allow-Originheaders forfetch()and.blob()to succeed in the browser. - Avoid tainted
<canvas>whenfetch()works: Drawing an image onto<canvas>and calling.toDataURL()also requires CORS (crossOrigin = "anonymous") and can re-encode lossy formats;fetch()+Blobpreserves the original file bytes.
3. Converting a Uint8Array / ArrayBuffer to Base64 in JS and Node.js
When working directly with binary buffers—such as in Node.js (fs.readFile()) or after await blob.arrayBuffer()—use Buffer in Node.js or chunked btoa() in standard JavaScript without mutating the source buffer:
// Convert an ArrayBuffer or Uint8Array to Base64 without mutating the input buffer
function bytesToBase64(bufferLike) {
let bytes;
if (bufferLike instanceof ArrayBuffer) {
bytes = new Uint8Array(bufferLike);
} else if (ArrayBuffer.isView(bufferLike)) {
bytes = new Uint8Array(bufferLike.buffer, bufferLike.byteOffset, bufferLike.byteLength);
} else {
throw new TypeError("Expected an ArrayBuffer or typed array view.");
}
if (typeof Buffer !== "undefined") {
return Buffer.from(bytes).toString("base64");
}
const chunkSize = 0x8000;
const chunks = [];
for (let i = 0; i < bytes.length; i += chunkSize) {
const slice = bytes.subarray(i, i + chunkSize);
chunks.push(String.fromCharCode.apply(null, slice));
}
return btoa(chunks.join(""));
}
// Example usage:
const sampleBytes = new TextEncoder().encode("Hi");
console.log(bytesToBase64(sampleBytes)); // "SGk="
- Chunked
btoa()avoids call-stack limits: Passing huge arrays directly toString.fromCharCode(...bytes)can overflow the call stack; chunking by0x8000(32,768) bytes avoids that limit. - Node.js
fs.promises.readFile(): In Node.js, you can read an image file directly viaconst buf = await fs.readFile("photo.png"); const b64 = buf.toString("base64");.
TL;DR: Use FileReader.readAsDataURL(fileOrBlob) wrapped in a Promise for files/blobs, or fetch(url) -> .blob() -> readAsDataURL() for image URLs (with CORS enabled), splitting after "," if you only want the raw Base64 string without the data:image/...;base64, prefix.
