Last updated
What Is a Data URI?
A data URI (also called data URL) embeds file content directly in a URL string, eliminating the need for a separate HTTP request. The format is defined in RFC 2397. Data URIs are commonly used to embed small images, fonts, and SVGs directly in HTML or CSS, reducing the number of network requests.
Data URI Format
data:[mediatype][;base64],data
Examples:
data:text/plain;charset=utf-8,Hello%20World
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...
data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'%3E...
data:application/json;base64,eyJrZXkiOiJ2YWx1ZSJ9
Converting Files to Data URIs
// File to data URI (browser)
function fileToDataUri(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = reject;
reader.readAsDataURL(file);
});
}
// String to data URI
function textToDataUri(text, mimeType = 'text/plain') {
return `data:${mimeType};charset=utf-8,${encodeURIComponent(text)}`;
}
// Data URI to Blob (for downloading)
function dataUriToBlob(dataUri) {
const [header, data] = dataUri.split(',');
const mimeType = header.match(/:(.*?);/)[1];
const isBase64 = header.includes(';base64');
const bytes = isBase64
? atob(data)
: decodeURIComponent(data);
const arr = new Uint8Array(bytes.length);
for (let i = 0; i < bytes.length; i++) arr[i] = bytes.charCodeAt(i);
return new Blob([arr], { type: mimeType });
}
When to Use Data URIs
Data URIs are best for small files (under 5KB). Larger files encoded as Base64 are ~33% bigger than the original and cannot be cached separately by the browser. For images over 5KB, a regular URL with proper caching headers is more efficient.