View on GitHub

Local File to DataURI (base64)

A cross-browser solution to read a local file and provide the base64 encoded content

Download this project as a .zip file Download this project as a tar.gz file

Example

For the browsers that don't support the FileReader API we'll load a Flash object.

Result:

How to use

You need to download the SWFObject 2.2 files from Google. It will be used to load the Flash if the FileReader API is not available. Or use the ones into this repository

You also need to download FileToDataURI.swf (available in my GitHub repo)

Call the swfobject file and jQuery (jQuery is only use here for this example):

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="dist/swfobject/swfobject.js"></script>
        

The HTML code for the example is very simple -- we use an object:

<object id="file-object"></object>
<div id="file-result"></div>

And the Javascript:

// it's the function called by the swf file
var Flash = {
  /* Flash.getFileData() is called after the file has been read */
  getFileData: function(base64) {
    showResult(base64)
  },
  /* getButtonLabel() permits to define another label for the "Load a file" button in the Flash version */
  getButtonLabel: function() {
    return "Load a file";
  }
};

// we just want to show the result into the div
function showResult(b) {
  $('#file-result').text(b)
}

// check if the FileReader API exists... if not then load the Flash object
if (typeof FileReader !== "function")
  // we use 80px by 23px, because we want the object to have the same size than the button
  swfobject.embedSWF("dist/FileToDataURI.swf", "file-object", "80px", "23px", "10", "dist/swfobject/expressInstall.swf", {}, {}, {});
else {
  // replace the <object> by an input file
  $('#file-object').replaceWith('<input type="file" id="file-object" value="Load a file" />');
  $('#file-object').on('change', function(e) {
    var files = e.target.files,file;

    if (!files || files.length == 0) return;
    file = files[0]; // in `file` you have the file properties like "name" and "size"
    
    var fileReader = new FileReader();
    fileReader.onload = function (e) {
      // ATTENTION: to have the same result than the Flash object we need to split
      // our result to keep only the Base64 part
      showResult(e.target.result.split(",")[1]);
    };
    fileReader.readAsDataURL(file);
  });
}

Good to know

The first time that someone will see the page, he'll have to download several files (see Readme), but then no more download is required so it will be much faster for all the other times.

Tested with IE7, IE8, IE9, Firefox 3.6 and Firefox 14, but it should work in all browsers if they have at least Flash v10.