7

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.

Amit Gandole
  • 431
  • 6
  • 16
  • 1
    if you want to avoid any framework or library its gonna be not pretty for you as localStorage is not the best API to support what you need and browsers tend to support one thing better than the other, plus in-browser persistence is hardly a true persistence as there are quotas etc. Consider this library: https://github.com/localForage/localForage it wraps all various persistences into a nice API – Sergey Rudenko Nov 15 '18 at 23:50
  • Thanks for this. It will help me in future. – Amit Gandole Nov 16 '18 at 06:33

2 Answers2

7

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"); }); 
Jonathan
  • 119
  • 1
  • I did that. But again came to CORS issues. After that I have asked this question. I need some another clean solution. – Amit Gandole Nov 15 '18 at 11:52
  • If you get a cors issue, then you asked the absolut wrong question. Because you only get a cors issue, when you make request to a server. So can you show your request code? I think the reason are the headers – Jonathan Nov 15 '18 at 12:30
  • Can I add my script in window.addEventListener?? Because I tried and page not displaying as expected. But after removing script, Alert() is showing and also my script running as expected. – Amit Gandole Nov 15 '18 at 13:06
  • I used ononline and onoffline functions in my html. and it quite runs well. Problem is that its not working in chrome. Also the in mozilla there is no cors issue i handled it through crossorigin but same issue remain in chrome. – Amit Gandole Nov 15 '18 at 13:11
  • localstorage has a relatively small disk space (2-10Mb), you may run out of space if you're not careful – user1432181 Jan 14 '21 at 21:20
2

I would suggest you use the local folder where you will save your file and its reference [ex, path] save in indexed DB.

You can sync image when you have an internet connection. This is how your HTML code looks:

 <div class="form-group col-md-12 col-sm-12 col-xs-12" >
     <label for="agreement_img">Upload billede:</label>
     <input type="file" class="form-control image1" id="image1" name="image1">
</div>

Your javascript code to save offline Image

if( document.getElementById("image1").files.length != 0 ){
            var files1 = $('#image1')[0].files[0];
            writeImage(files1.name, files1,1);    
  }

 var OfflineArray = {};
  var SIZE = 100 * 1024 * 1024; // 100 MB

  var errorFct = function (e) {
    console.error(e);
  };

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


  var createTempName = function () {
    return 'temp.name.dummy.jpg';
  };

  var addToSyncQueue = function (filename) {
    // adding to sync queue
    console.log('Adding to queue', filename);
  };

  var showImage = function (fileName,imgno) {
    var src = 'filesystem:' + window.location.origin + '/persistent/' + fileName;
    return src;

  };

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

          fileEntry.file(successFct, errorFct);

        }, errorFct);
      }
    );
  };

  var writeSuccessFull = function (fileName,imgno) {
    //addToSyncQueue(fileName);

    var imgfile = showImage(fileName,imgno);
    console.log(imgfile);
    var cnt = localStorage.getItem('cnt');
    localStorage.setItem("offlineimg"+ cnt +"_"+ imgno, imgfile);
  };

  function writeImage(fileName, file,imgno) {
    getFileSystem(function (fileSystem) {
      fileSystem.root.getFile(fileName, {create: true}, function (fileEntry) {

        fileEntry.createWriter(function (fileWriter) {
          fileWriter.onwriteend = writeSuccessFull(fileName,imgno);

          fileWriter.onerror = errorFct;

          fileWriter.write(file);

        }, errorFct);

      });
    });
  }