JavaScript 的 Base64

本文汇总 JavaScript 在浏览器与 Node.js 环境中的 Base64 用法, 涵盖 btoa/atob、UTF-8 安全处理方法、URL 安全变体, 以及字符串、二进制与文件相关示例。

概览

Base64 使用可打印字符来表示二进制数据。 在浏览器中,btoa() 将二进制字符串编码为 Base64,atob() 负责解码; 涉及非 ASCII 文本时,请配合 TextEncoder/TextDecoder 进行 UTF-8 安全处理。 在 Node.js 中,请使用 Buffer

API 参考

快速示例

浏览器:UTF-8 安全处理

// Encode a JS string (UTF-8) to Base64
function encodeBase64(text) {
	const bytes = new TextEncoder().encode(text);
	let binary = "";
	for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
	return btoa(binary);
}

// Decode Base64 to JS string (UTF-8)
function decodeBase64(b64) {
	const binary = atob(b64);
	const bytes = new Uint8Array(binary.length);
	for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
	return new TextDecoder('utf-8', { fatal: false }).decode(bytes);
}

console.log(encodeBase64('Hello, 世界')); // SGVsbG8sIOS4lueVjw==
console.log(decodeBase64('SGVsbG8sIOS4lueVjw=='));

Node.js:Buffer

// String → Base64
const b64 = Buffer.from('Hello, 世界', 'utf8').toString('base64');
console.log(b64); // SGVsbG8sIOS4lueVjw==

// Base64 → String
const text = Buffer.from('SGVsbG8sIOS4lueVjw==', 'base64').toString('utf8');
console.log(text); // Hello, 世界

URL 安全的 Base64

// Replace +/ with -_, optionally remove padding =
function toUrlSafe(b64, stripPadding = false) {
	let s = b64.replace(/\+/g, '-').replace(/\//g, '_');
	return stripPadding ? s.replace(/=+$/g, '') : s;
}

function fromUrlSafe(urlSafeB64) {
	let s = urlSafeB64.replace(/-/g, '+').replace(/_/g, '/');
	// pad to length % 4 === 0
	while (s.length % 4) s += '=';
	return s;
}

const safe = toUrlSafe('YWJj+/==');
console.log(safe);
console.log(fromUrlSafe(safe));

二进制与文件(浏览器)

// File → Base64 (data URL or raw Base64)
function fileToBase64(file, callback) {
	const reader = new FileReader();
	reader.onload = () => {
		const dataUrl = reader.result; // e.g. "data:image/png;base64,iVBORw0KG..."
		const base64 = String(dataUrl).split(',')[1];
		callback({ dataUrl, base64 });
	};
	reader.readAsDataURL(file);
}

// Base64 → Blob (download)
function base64ToBlob(b64, contentType = 'application/octet-stream') {
	const binary = atob(b64);
	const bytes = new Uint8Array(binary.length);
	for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
	return new Blob([bytes], { type: contentType });
}

注意事项