Image storage when offline in PWA
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"); });
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);
});
});
}