Skip to content

Instantly share code, notes, and snippets.

@Muzietto
Last active October 11, 2015 19:20
Show Gist options
  • Save Muzietto/1a9b2965f5cd21344426 to your computer and use it in GitHub Desktop.
Save Muzietto/1a9b2965f5cd21344426 to your computer and use it in GitHub Desktop.
HTML5 FileReader to load CSV file in page and use it as JS variable
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<title>FileWriter API</title>
<style>
body { font-family: Verdana; font-size: 1.5em; }
.horizon { width: 500px; margin: 0 auto; padding: 10px; border: 2px solid red; }
.horizon input, .horizon label { margin: 10px; }
.horizon input { width: 400px; height: 2em; }
</style>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
'use strict';
$(document).ready(function(){
$('#inputfile').change(function(data){
var selectedFile = $('#inputfile').get(0).files[0];
var reader = new FileReader();
reader.onloadend= function(e) {
var data = e.target.result;
var base64 = data.split('base64,')[1];
var csv = atob(base64);
alert('var csv = ' + csv);
};
reader.readAsDataURL(selectedFile);
});
});
</script>
</head>
<body>
<h1 style="margin-left:20px;">load CSV file into browser memory</h1>
<div id="mainDiv" class="horizon">
<input type="file" class="" id="inputfile"/>
</div>
</body>
</html>
key value
name marco
surname faustinelli
nickname muzietto
@Muzietto
Copy link
Author

Minimalist sample usage of HTML5 FileWriter API. A csv file is read from disk and assigned to a JS variable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment