Data URLs are a special type of URL that allows you to embed small files directly into HTML, CSS, or JavaScript code as a string of text. This guide explains what Data URLs are, how they work, and when to use them in your web development projects.
A Data URL (also known as a Data URI) is a URI scheme that allows you to include data inline in web pages as if they were external resources. Instead of pointing to a file location, a Data URL contains the actual content of the file, typically encoded in Base64 format.
The general syntax of a Data URL is:
data:[<media type>][;base64],<data>
For example, a simple red dot image as a Data URL might look like this:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==
When a browser encounters a Data URL, it decodes the data and processes it as if it had been fetched from an external source. The process works like this:
data:
prefiximage/png
, text/html
);base64
)A Data URL consists of several parts:
data:
image/png
, text/plain
). If omitted, defaults to text/plain;charset=US-ASCII
;base64
if the data is Base64 encodedUsing Data URLs offers several advantages:
Data URLs also have some important limitations to consider:
Data URLs are particularly useful in these scenarios:
Here are examples of Data URLs for different types of content:
data:text/plain;charset=UTF-8,Hello%20World!
data:text/html;charset=UTF-8,<h1>Hello%20World!</h1>
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==
data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/></svg>
Data URLs are supported in all modern browsers, including:
However, there are some browser-specific limitations to be aware of:
You can convert files to Data URLs using various methods:
The easiest way is to use our Data URL Converter tool, which allows you to upload an image and get its Data URL representation instantly.
You can also convert files to Data URLs programmatically using JavaScript:
function fileToDataURL(file, callback) {
const reader = new FileReader();
reader.onload = function(e) {
callback(e.target.result);
};
reader.readAsDataURL(file);
}
// Example usage
const fileInput = document.querySelector('input[type="file"]');
fileInput.addEventListener('change', function() {
if (this.files && this.files[0]) {
fileToDataURL(this.files[0], function(dataUrl) {
console.log(dataUrl);
// Use the Data URL here
});
}
});