js使用FileReader读取上传csv文件
使用 FileReader 读取 csv 档
<script>
function readCsv(elem) {
const file = elem.files[0];
if (file.type != "text/csv") {
alert("文件类型错误");
return;
}
var reader = new FileReader();
reader.onload = function () {
const result = reader.result;
let lines = result.split("\r\n");
lines.map(function (str, index) {
if (str.length > 0) {
let line = safeSplit(str);
console.log(line);
}
});
};
reader.readAsText(file, "Big5"); //指定编码
}
//避免字符中含有','时被分开
function safeSplit(str) {
let inQuotes = false;
return str.split("").reduce(
(acc, char) => {
if (char === '"') inQuotes = !inQuotes;
if (char === "," && !inQuotes) {
acc.push("");
} else if (char != '"') {
acc[acc.length - 1] += char;
}
return acc;
},
[""]
);
}
</script>
<input type="file" name="file" id="uploadFile" accept=".csv" onchange="readCsv(this);" />
测试文档内容
![]()
数据

浙公网安备 33010602011771号