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.
1 2 3 4 |
|
When the user select a file, we want to store the image.
1 2 3 4 5 6 |
|
The image storage is handled by this method.
1 2 3 4 5 6 7 8 9 10 11 |
|
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.
1 2 3 4 5 6 |
|
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.
1 2 3 4 5 6 7 8 9 10 |
|
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
1 2 3 4 5 6 7 8 9 10 |
|
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.