I need my code to be able to take data from a csv file and print it to the screen. At the moment it takes data from a txt file fine but a CSV will just return "file not supported". Here is my code.
<html>
<div id="page-wrapper">
<div>
Select a text file:
<input type="file" id="fileInput">
</div>
<pre id="fileDisplayArea"><pre>
</div>
<button onClick="test()">Show Text</button>
<script>
function test (){
var file = fileInput.files[0];
var textType = /text.*/;
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function(e) {
var look = reader.result;
window.alert (look);
}
reader.readAsText(file);
} else {
fileDisplayArea.innerText = "File not supported!";
}
}
</script>
asked Oct 31, 2016 at 12:33
Alex Newport
611 gold badge1 silver badge7 bronze badges
1 Answer 1
The type property of the file object is the type that the OS provides, based on the extension of the file.
On windows, the filetype of csv files is application/vnd.ms-excel, so when you check:
file.type.match(/text.*/)
It's false.
You can use change your code to check for any of text.* or application/vnd.ms-excel:
var textType = /text.*/;
var csvType = 'application/vnd.ms-excel';
if (file.type.match(textType) || file.type == csvType) {
Another option is to check the extension of the file:
if (file.name.endsWith('.csv')) {
...
}
answered Oct 31, 2016 at 12:40
Dekel
62.9k12 gold badges109 silver badges130 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
default