Reputation: 759
I'm making a local html5 stats page using Highcharts, and I want to get the data for my charts from a csv file allocated in my own laptop. The javascript code is:
var arch = new FileReader();
var content = arch.readAsArrayBuffer('./csvs/sample1.csv');
//var content = arch.readAsText('./csvs/sample1.csv'.files);
var sample = $.csv.toArrays(content);
console.log(sample1);
$(function () {
$('#container').highcharts({
xAxis: {
min: -0.5,
max: 5.5
},
yAxis: {
min: 0
},
title: {
text: 'Scatter plot with regression line'
},
series: [{
type: 'line',
name: 'Regression Line',
data: [[0, 1.11], [5, 4.51]],
marker: {
enabled: true
},
states: {
hover: {
lineWidth: 0
}
},
enableMouseTracking: false
}, {
type: 'scatter',
name: 'Observations',
data: sample,
marker: {
radius: 4
}
}]
});
});
I'm using jquery-csv plugin too, but it doesn't work. I've tested with fopen but nothing too. The console tells me:
Uncaught TypeError: Failed to execute 'readAsArrayBuffer' on 'FileReader': parameter 1 is not of type 'Blob'.
Thanks.
Upvotes: 0
Views: 1775
Reputation: 20737
FileReader.readAsArrayBuffer(..)
expects a Blob as parameter, not a string. A blob is binary data, read from a file. You can find the documentation about FileReader on mdn.
It tells us that we can pass a File
(docs) instead too, which we can extract from a FileList
(docs).
You cannot read files directly from your computer. That would be a major security breach. What we need to do is have an input element where we either select the file, or where we drag-and-drop the file onto. Then we read the file and execute your code:
<input type="file" id="myfile"> <input type="button" id="csvbutton" value="Load">
And javascript:
$("#csvbutton").on( "click", function() {
var file = $("#myfile")[0].files[0];
if( file == undefined ) {
//RIP
return;
}
var arch = new FileReader();
var content = arch.readAsArrayBuffer(file);
//etc
} );
Upvotes: 0
Reputation: 66478
To read local file you need input type file:
function readSingleFile(evt) {
//Retrieve the first (and only!) File from the FileList object
var f = evt.target.files[0];
if (f) {
var r = new FileReader();
r.onload = function(e) {
var contents = e.target.result;
document.getElementById('output').innerHTML = contents;
}
r.readAsText(f);
} else {
alert("Failed to load file");
}
}
document.getElementById('fileinput').addEventListener('change', readSingleFile, false);
<input type="file" id="fileinput"/>
<textarea id="output" cols="60" rows="10"></textarea>
Upvotes: 1
Reputation: 17952
You need to read the file into an object, then pass that object to your FileReader.readAsXXX
method.
FileReader.readAsArrayBuffer()
doesn't take a string.
Here is some API docs for you that may help.
Upvotes: 0