ionic-frameworklocal-storageprogressive-web-appsoffline-mode

Image storage when offline in PWA


I am building Manual PWA (Not using framework IONIC,React etc.) for my existing hosted website. My basic requirement is I want to capture the picture from my phone camera. But conditions are: 1. When I am capturing the picture I will be totally offline. 2. I want to upload it to the server means in database. But as I am offline I want to store that in localstorage and when I get back online even after 3 days it will resume the remaining thing and automatically will upload the image to server.

I tried using javascript but didn't got that much. the basic approach i want is :

if(camera clicked)->
   if(upload btn clicked)-> 
        if(device is online)-> 
           upload to the server;
           (**or I can call one function here which can upload the image to server.)
        else if(device is offline)->
           upload to localstorage;
//again when device gets online I will call one **function(which is I am calling from **) in constructor which get executed everytime when site is reloaded or app is opened. 

My ** function will be :
upload()->
    if(device is online)->
      try looking into localstorage -> if image address is available ->
        upload_image_to server where src="address_of_image_in_localstorage".

I want to implement this using only html and javascript not any framework. The code I have added above is just guessed approach not any type of code. Please suggest any improved approach if have. And It will be better if anyone can help along with implemented code and not only informative answers.

Approach is just for android now but can suggest journal apporach if have for another platform for understanding.


Solution

  • I would recommend to first convert the image to base 64 and save it to your localstorage. There is an event called online, wich will detect when the user goes online again and there you can upload your image to the DB:

    window.addEventListener("online", function(){ alert("User is now online"); });