Top add

Locally Store image for faster uploads using HTML5

By storing my web page CSS, Javascript files or Images locally, I would have the added benefit of reduced network and server usage, in addition to improving page load times.  The HTML5 localStorage interface is a basic client-side key-value database, meaning data is saved and retrieved locally from the clients web browser storage.  However I hit an immediate challenge, as localStorage only supports String objects, and for my usage, I wanted to store binary Images.

Given this limitation in localStorage, the first step required for my implementation is to base64 encode the binary Images.   I found a website that offers an online tool to perform this encoding, however there are many shareware tools available to encode/decode binaries from your workstation or dynamically from a server application.  I converted my Images at OpinionatedGeek, which offers a simple web interface tool to quickly encode Images. Once you have base64 encoded your Images,  you will need to implement the Javascript and localStorage API to read & write your Images from the local client:

Javascript implementation:

  var hero;

  if ( localStorage.getItem('heroImg')) {
    hero = localStorage.getItem('heroImg');
  else {
    hero = '/9j/4AAQSkZJRgABAgAAZABkAAD/7    /.../    6p+3dIR//9k=';

  document.getElementById("hero-graphic").src='data:image/png;base64,' + hero;

The corresponding HTML Image element:
<img id="hero-graphic" alt="Blog Hero Image" src="" />

No comments: