Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ElvisLives/6675478 to your computer and use it in GitHub Desktop.
Save ElvisLives/6675478 to your computer and use it in GitHub Desktop.
This is an example of the FileReader api, using RSVP promises, and LocalStorage. It will open two files and wait for both files to be loaded before displaying the text of both files. If you load new files and submit it will clear them out of local storage and reload them from Local Storage into the two div tags.
<html>
<head>
<script src="http://rsvpjs-builds.s3.amazonaws.com/rsvp-latest.js"></script> // "rsvp-latest.js"
// Live example at http://jsfiddle.net/Elvislives/XVv3G/3/
<title>File Reader With Promises RSVP and LocalStorage</title>
<style type="text/css">
</style>
</head>
<body>
<p>
<input type="file" id="firstFile"/>
<input type="file" id="secondFile"/>
<button id="submit">Submit</button>
</p>
<span>First File</span>
<div id="firstFileDiv" style="min-width: 300px; height: 350px; margin: 1em"></div>
<span>Second File</span>
<div id="secondFileDiv" style="min-width: 300px; height: 350px; margin: 1em"></div>
</body>
<script type="text/javascript">
const firstFileName = 'firstFile';
const secondFileName = 'secondFile';
function handleFileSelect(evt) {
var previousReport = document.getElementById(firstFileName).files[0];
var currentReport = document.getElementById(secondFileName).files[0];
var previousFileReader = new FileReader();
var currentFileReader = new FileReader();
var previousLoadPromise = new RSVP.Promise(function(resolve,reject){
previousFileReader.addEventListener("load", function (event) {
console.log('I read the first File');
window.localStorage.removeItem(firstFileName);
window.localStorage[firstFileName] = event.target.result;
resolve();
});
});
var currentLoadPromise = new RSVP.Promise(function(resolve,reject){
currentFileReader.addEventListener("load", function (event) {
console.log('I read the second File');
window.localStorage.removeItem(secondFileName);
window.localStorage[secondFileName] = event.target.result;
resolve();
});
});
RSVP.all([previousLoadPromise, currentLoadPromise]).then(function(){
console.log('I waited for the files');
var first = document.getElementById("firstFileDiv");
first.textContent = window.localStorage[firstFileName];
var second = document.getElementById("secondFileDiv");
second.textContent = window.localStorage[secondFileName];
});
previousFileReader.readAsText(previousReport);
currentFileReader.readAsText(currentReport);
}
document.getElementById('submit').addEventListener('click', handleFileSelect, false);
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment