HTML5: Offline upload of images
/*global $ */ | |
$(function () { | |
'use strict'; | |
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) { | |
var src = 'filesystem:' + window.location.origin + '/persistent/' + fileName; | |
var img = $('<img />').attr('src', src); | |
$('.js-image-container').append(img); | |
}; | |
var readImage = function (fileName, successFct) { | |
getFileSystem(function (fileSystem) { | |
fileSystem.root.getFile(fileName, {}, function (fileEntry) { | |
fileEntry.file(successFct, errorFct); | |
}, errorFct); | |
} | |
); | |
}; | |
var writeSuccessFull = function () { | |
addToSyncQueue(fileName); | |
showImage(fileName); | |
}; | |
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); | |
}); | |
}); | |
} | |
$(document).on('change', '.js-image-upload', function (event) { | |
var file = event.target.files[0]; | |
var fileName = createTempName(file); | |
writeImage(fileName, file); | |
}); | |
}); |
<!DOCTYPE html> | |
<html> | |
<head> | |
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> | |
<script src="application.js"></script> | |
<title></title> | |
</head> | |
<body> | |
<input type="file" accept="image/*" class="js-image-upload"/> | |
<div class="js-image-container"></div> | |
</body> | |
</html> |
This comment has been minimized.
This comment has been minimized.
Hello Nice Article. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This comment has been minimized.
Hey Johannes, great work mate! I only just found this via your blog post, have been looking for a solution like this for sites/apps running entirely offline via a USB (for long-distance users with no internet connection). Really good work.
Only enhancement I could suggest is if we were able to serve the image file as a thumbnail, so there's a visual representation instead of a filename. If I get time I'll try it myself and fork it.