Reading CSV File With Javascript and HTML5 File API

Search for a command to run...

No comments yet. Be the first to comment.
Introduction Django-Syzygy is a Django companion that makes database migrations safer in real production environments. It focuses on one specific, painful problem: migrations that are technically valid, but unsafe during rolling deployments. Syzygy w...

Master the core building blocks of Kafka, including partitions, consumer groups, and how to handle tricky topic migrations.

Avoiding Downtime in Django Migrations with django-migration-linter Deploying Django apps with zero downtime is essential in modern production systems, especially when rolling out updates on Kubernetes or deploying worker-based systems incrementally....

Building beautiful, responsive forms in Django doesn’t have to be a painful experience. By combining the power of django-tailwind with django-widget-tweaks and a few well-crafted custom CSS classes, you can create stunning, consistent forms that look...

What is HTMX? HTMX is a powerful tool that allows developers to create highly interactive and dynamic user interfaces without the need for heavy JavaScript frameworks. At its core, HTMX uses HTML attributes to define behaviour, making it an ideal com...

In a specific project, the client want to read a CSV file, process and show data into an OpenLayers Map.
So it come in my mind to write a simple html/javascript application, without any backend server.
The unique constraint was how can I read the CSV file in browser.
HTML5 finally provides a standard way to interact with local files, via the File API
We are going to use FileReader
First, let’s check if the browser support FileReader API
function handleFiles(files) {
// Check for the various File API support.
if (window.FileReader) {
// FileReader are supported.
} else {
alert('FileReader are not supported in this browser.');
}
}
To select a file we’re going to use a simple html <input type="file">
We just call handleFile to make JavaScript returns the list of selected File objects but we are going to use only one.
<script type="text/javascript" src="static/js/read-csv.js"></script>
<input type="file" id="csvFileInput" onchange="handleFiles(this.files)"
accept=".csv">
##Reading the File
After we’ve obtained a File reference, we instantiate a FileReader object to read its contents into memory. When the load finishes, the reader’s onload event is fired and its result attribute can be used to access the file data.
FileReader includes four options for reading a file, asynchronously:
FileReader.readAsBinaryString(Blob|File) – The result property will contain the file/blob’s data as a binary string. Every byte is represented by an integer in the range [0..255].FileReader.readAsText(Blob|File, opt_encoding) – The result property will contain the file/blob’s data as a text string. By default the string is decoded as ‘UTF-8’. Use the optional encoding parameter can specify a different format.FileReader.readAsDataURL(Blob|File) – The result property will contain the file/blob’s data encoded as a data URL.FileReader.readAsArrayBuffer(Blob|File) – The result property will contain the file/blob’s data as an ArrayBuffer object.For our example, we want to read a CSV file, so we can read it as text. And perfom data processing after in processData(csv) function.
function handleFiles(files) {
// Check for the various File API support.
if (window.FileReader) {
// FileReader are supported.
getAsText(files[0]);
} else {
alert('FileReader are not supported in this browser.');
}
}
function getAsText(fileToRead) {
var reader = new FileReader();
// Read file into memory as UTF-8
reader.readAsText(fileToRead);
// Handle errors load
reader.onload = loadHandler;
reader.onerror = errorHandler;
}
function loadHandler(event) {
var csv = event.target.result;
processData(csv);
}
function processData(csv) {
var allTextLines = csv.split(/\r\n|\n/);
var lines = [];
for (var i=0; i<allTextLines.length; i++) {
var data = allTextLines[i].split(';');
var tarr = [];
for (var j=0; j<data.length; j++) {
tarr.push(data[j]);
}
lines.push(tarr);
}
console.log(lines);
}
function errorHandler(evt) {
if(evt.target.error.name == "NotReadableError") {
alert("Canno't read file !");
}
}
That’s it.