Creating a data URI from a file

Data URIs are a way of making a URI that actually contains the data inside it. They’re useful when you want to include normally external resources within another file (in my instance, including images in user styles).

The data URI kitchen is an online resource that lets you generate data URIs from files. But what if you want to do the same from within an extension?

This function returns a base 64-encoded data URI from the passed nsIFile. Line breaks added to prevent format problems in this post.

function generateDataURI(file) {
	var contentType = Components.classes["@mozilla.org/mime;1"]
		.getService(Components.interfaces.nsIMIMEService).getTypeFromFile(file);
	var inputStream = Components.classes["@mozilla.org/network/file-input-stream;1"]
		.createInstance(Components.interfaces.nsIFileInputStream);
	inputStream.init(file, 0x01, 0600, 0);
	var stream = Components.classes["@mozilla.org/binaryinputstream;1"]
		.createInstance(Components.interfaces.nsIBinaryInputStream);
	stream.setInputStream(inputStream);
	var encoded = btoa(stream.readBytes(stream.available()));
	return "data:" + contentType + ";base64," + encoded;
}

This code is now available at the Mozilla Developer Center.

One Response to “Creating a data URI from a file”

  1. LouCypher Says:

    Thanks, Jason
    It worked perfectly :D

Leave a Reply

Adventures in development - Web standards and Firefox extensions