Skip to content

Instantly share code, notes, and snippets.

@codeguy
Created September 24, 2013 01:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save codeguy/6679344 to your computer and use it in GitHub Desktop.
Save codeguy/6679344 to your computer and use it in GitHub Desktop.
Upload, parse, and iterate CSV file with HTML5 File APIs
/**
* 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);
@apnerve
Copy link

apnerve commented Jan 8, 2018

This might not work on some windows systems as the filetype obtained is application/vnd.ms-excel. Reference

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