About Johannes Thones

Johannes is a Software-Developer, ThoughtWorker, Permanent Journeyman, Ruby Enthusiast, Java and Devils Advocate. He lives and works in Hamburg, Germany.

HTML5: Offline upload of images

I am currently working on an application which has needs to work offline. This has the beneficial side effect, we use the different HTML5 storage capabilities. One of the is the File API, which we are using to store images locally – before queuing them for upload to a backend server.

In this article, I will share some code how we did this. The example works in Google Chrome – for DOM manipulation I will use JQuery.

Starting simple, we have one file input for images and an area to show the uploaded images.
 

<body>
 <input type="file" accept="image/*" class="js-image-upload"/>
 <div class="js-image-container"></div>
</body>

When the user select a file, we want to store the image.

$(document).on('change', '.js-image-upload', function (event) {
  var file = event.target.files[0];
  var fileName = createTempName(file);

  writeImage(fileName, file);
});

The image storage is handled by this method.

function writeImage(fileName, file) {
  getFileSystem(function (fileSystem) {
    fileSystem.root.getFile(fileName, {create: true}, function (fileEntry) {
      fileEntry.createWriter(function (fileWriter) {
        fileWriter.onwriteend = writeSuccessFull;
        fileWriter.onerror = errorFct;
        fileWriter.write(file);
      }, errorFct);
    });
  });
}

What is happening here?

  • Retrieve the file system
  • Create a file by the specificied name on its root
  • Create a writer for this file
  • Configure a success and error callback when the asynchronous file write happend
  • Write the blob of the file using the writer

The retrieval of the file system is a two step procedure. We need to request quota from the browser and than get the file system.

var SIZE = 100 * 1024 * 1024; // 100 MB
var getFileSystem = function (successFct) {
  navigator.webkitPersistentStorage.requestQuota(SIZE, function () {
    window.webkitRequestFileSystem(window.PERSISTENT, SIZE, successFct, errorFct);
  }, errorFct);
};

The user will be asked to grant the website the access to a persistent storage. There are some errors you can get, e.g. when the user does not accept our request.

But let’s assume the user trusts us. Then we want to react to the successful write and show the image. We can use a local file storage url and add the file to a queue to upload the file to the server.

var showImage = function (fileName) {
  var src = 'filesystem:' + window.location.origin + '/persistent/' + fileName;
  var img = $('<img />').attr('src', src);
  $('.js-image-container').append(img);
};

var writeSuccessFull = function () {
  addToSyncQueue(fileName);
  showImage(fileName);
};

I’m omitting the queue logic here. You can keep a queue of images for uploaded in the web storage or IndexedDB of your application. To read the image from storage you can use something like this

var readImage = function (fileName, successFct) {
  getFileSystem(function (fileSystem) {
    fileSystem.root.getFile(fileName, {}, function (fileEntry) {

        fileEntry.file(successFct, errorFct);

      }, errorFct);
    }
  );
};
  • So this is a brief overview of what we did here. The working example code can be found here: https://gist.github.com/jthoenes/3668856a188d600e02d6

Hope it has been useful to a few people dealing with similar issues. Feel free to ask questions, when something pops up in your mind.

Reference: HTML5: Offline upload of images from our JCG partner Johannes Thones at the Johannes Thönes blog blog.
Related Whitepaper:

Software Architecture

This guide will introduce you to the world of Software Architecture!

This 162 page guide will cover topics within the field of software architecture including: software architecture as a solution balancing the concerns of different stakeholders, quality assurance, methods to describe and evaluate architectures, the influence of architecture on reuse, and the life cycle of a system and its architecture. This guide concludes with a comparison between the professions of software architect and software engineer.

Get it Now!  

Leave a Reply


5 − = one



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close