I wanted to be able to load a text file on a page; specifically, a CSV file for my purposes.
The idea is to load a text file and do some data analysis.
The code uses a built-in browser object FileReader
and displays the result. Here's a simple implementation:
<input type="file" accept="text/csv, text/txt" onchange="onFileInput(event)" />
<pre id=o></pre>
<script>
const handleData = text => {
// do stuff with text data here
o.innerHTML = text;
};
const onFileInput = e => {
r = new FileReader();
r.onload = _ => handleData(r.result);
r.readAsText(e.target.files[0]);
};
</script>
This could be a starting point for a text file loading tool such as viewing a CSV file into a nicely formatted table.
data:text/html,<input type=file accept=text/csv,text/txt onchange="r=new FileReader;r.onload=_=>o.innerHTML=r.result;r.readAsText(event.target.files[0])" /><pre id=o>