I'm trying to parse some data from my local directory. I use papa parser to do it. The problem is I can't assign text file into a variable. I'm getting this error ;
Uncaught TypeError: Failed to execute 'readAsText' on 'FileReader': parameter 1 is not of type 'Blob'.
I've searched about it and I've seen that it is a very common error when reading files with HTML file reader .
My code is ;
<!doctype html>
<html class="no-js" lang="">
<head>
<script src="https://github.com/mholt/PapaParse/blob/master/papaparse.js"></script>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Parse Example</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/main.css">
<script src="js/vendor/modernizr-2.8.3.min.js"></script>
</head>
<p>Click the button to Upload .</p>
<button onclick="myFunction()" type="INPUT">Load</button>
<input type="file" name="datafile" size="40">
<script>
var x;
var config = {
delimiter: "", // auto-detect
newline: "", // auto-detect
header: true,
dynamicTyping: false,
preview: 0,
encoding: "",
worker: false,
comments: false,
step: undefined,
complete: undefined,
error: undefined,
download: true,
skipEmptyLines: false,
chunk: undefined,
fastMode: undefined,
beforeFirstChunk: undefined,
withCredentials: undefined
};
function myFunction() {
x = document.getElementsByName("datafile");
myfile = Papa.parse(x, config);
document.getElementById("demo").innerHTML = myfile;
}
</script>
<p id="demo"></p>
</body>
</html>
getElementsByName
returns always returns nodelist collection of the matched elements, so basically you can just select first one: x = document.getElementsByName("datafile")[0]
Papa.parse
expects its first argument to be string or File
object. File
object can be obtained from FileList
, which stored in files
property of the file input. So basically (it should work if file is selected in the input):
x = document.getElementsByName("datafile")[0].files[0]
As documentaion says Papa.parse
doesn't return anything itself, you should provide callback to get the data. So if you replace complete: undefined
in config
object with something like
complete: function(data) {
console.log(data);
}
you'll get your data displayed in the browser console.