Converting a File to a Base64 DataURL in JavaScript

The code included below prompts the user to select a file, loads that file, and displays its contents in a text box as a DataURL encoded in Base64 characters.  To see it in action, copy it into an .html file and open that file in a web browser that runs JavaScript. Or, for an online version, visit https://thiscouldbebetter.neocities.org/filetodataurl.html.

This utility was originally written to provide a way to use images and other media in a JavaScript program running from the local filesystem (“file://”) without falling afoul of security restrictions in certain web browsers that are designed to prevent that sort of thing.

<html>
<body>

	<p>Select a File to Load:</p>
	<input id="inputFileToLoad" type="file" onchange="loadImageFileAsURL();" />
	

	<p>File Contents as DataURL:</p>
	<textarea id="textAreaFileContents" style="width:640;height:240" ></textarea>

<script type="text/javascript">

function loadImageFileAsURL()
{
	var filesSelected = document.getElementById("inputFileToLoad").files;
	if (filesSelected.length > 0)
	{
		var fileToLoad = filesSelected[0];

		var fileReader = new FileReader();

		fileReader.onload = function(fileLoadedEvent) 
		{
			var textAreaFileContents = document.getElementById
			(
				"textAreaFileContents"
			);
	
			textAreaFileContents.innerHTML = fileLoadedEvent.target.result;
		};

		fileReader.readAsDataURL(fileToLoad);
	}
}

</script>

</body>
</html>

Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

14 Responses to Converting a File to a Base64 DataURL in JavaScript

  1. Thomas says:

    Do you know if the opposite is possible, that is to say convert Base64 data to a File object ?

    • Possible? Certainly. But you can’t really adapt this code to do it, and I don’t really have anything else prepared on this site that will either.

      This is almost definitely way more effort than anyone would want to put into it, but if you’re really hard up you might try looking at the Base64Encoder class from a previous post on this site, updating it to transform things from Base64 to bytes rather than the other way around, and then using the code from another post to download the resulting file to your local machine.

    • Actually, I went ahead and expanded the Base64Encoder so that it not only converts bytes to Base64 digits, but also converts Base64 digits back to bytes. Please see this post for details.

  2. Pingback: Encoding a image to base64 and upload to web service in Phonegap | SuperBlog

  3. Jobran Jubair says:

    thank you so much, you saved my day, good job and i really appreciate it

  4. Jesse says:

    thank you for this publication

  5. I have added a runnable version of this program at my companion site at the URL https://thiscouldbebetter.neocities.org/filetodataurl.html. Ordinarily, I would update the post itself to add this note, but unfortunately edits to my HTML code listings currently fall afoul of errors in the WordPress editor, so I currently can’t make any edits to the post itself without “fixing” (that is, breaking) the code in the code listing.

    • Okay, I’ve added the link to the online version in the main body of the post, and put the code inside WordPress’s custom “code” tag. It mostly looks okay, though I think a couple of line breaks got lost.

  6. Helam Moreira says:

    Thanks.
    This is very usefull!!

  7. Gracias colega, saludos desde México

  8. Triven says:

    Thanks man…you rock \m/

  9. Sukhbir Singh says:

    how to store this encoded base64 string in the database by php??

    thanks in advance 🙂

  10. Lucas says:

    Hey, nice article. How to wait until it finishes loading? In my test, with a 5MB audio file, it took minutes until the text box populated with base64 content. While debugging I noticed that the debugger passes through all lines of the code. How to add a Call Back to notify the conversion was really finished? Thanks!

    • There’s technically already a callback, specifically, the anonymous function that’s being assigned to the FileReader’s onloaded event on line 22. The debugger appears to continue past the contents of this function because that’s just how asynchronous code works in JavaScript. If all you want is a more obvious notification that the conversion is complete, you might try adding a line of code like, say, “alert(‘Conversion complete’);” inside that function.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s