Created
September 24, 2013 01:44
-
-
Save codeguy/6679344 to your computer and use it in GitHub Desktop.
Upload, parse, and iterate CSV file with HTML5 File APIs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* CSV upload and parser | |
* | |
* This code will use the HTML5 File and FileReader APIs | |
* to upload and parse a CSV file. | |
* | |
* REQUIREMENTS: | |
* - jQuery | |
* - D3.js | |
* - HTML5 File APIs | |
*/ | |
(function ($) { | |
// DOM Element | |
var $fileInput = $('#file'), | |
$submitBtn = $('#submit'); | |
// On upload | |
var onUpload = function (e) { | |
e.preventDefault(); | |
// Validate is file | |
var fileList = $fileInput.get(0).files; | |
if (fileList.length === 0) { | |
fail('You must select a file'); | |
} | |
// Validate is CSV | |
var file = fileList[0]; | |
if (file.type !== 'text/csv') { | |
fail('Uploaded file must be a RFC4180-compliant CSV file'); | |
} | |
// Init file reader | |
var fileReader = new FileReader(); | |
fileReader.onload = function (e) { | |
processCsv(d3.csv.parse(fileReader.result)); | |
}; | |
fileReader.onerror = function (e) { | |
throw 'Error reading CSV file'; | |
}; | |
// Start reading file | |
fileReader.readAsText(file); | |
}; | |
// Process CSV | |
var processCsv = function (csvData) { | |
}; | |
// Bind upload button | |
$submitBtn.on('click', onUpload); | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This might not work on some windows systems as the filetype obtained is
application/vnd.ms-excel
. Reference