如何在将CSV文件上传至Express服务器前统计其行数?
实现上传前统计CSV行数的方案
核心思路
通过前端JavaScript直接读取选中的本地CSV文件内容,在浏览器内完成行数统计,无需提前上传至服务器。
修改后的代码实现
1. 优化HTML(可选增强)
<input type="file" name="data_file" id="name" required accept=".csv"> <button type="button" onclick="confirm()"> Submit </button> <div class="confirm" style="display:none;"> <div id="details"></div> </div>
添加accept=".csv"可限制仅选择CSV文件,减少无效操作
2. 重写confirm()函数实现行数统计
function confirm() { const fileInput = document.getElementById('name'); const file = fileInput.files[0]; if (!file) { alert('请先选择CSV文件'); return; } // 直接获取文件名,比解析路径更可靠 const fileName = file.name; // 创建文件读取器 const reader = new FileReader(); reader.onload = function(e) { const content = e.target.result; // 基础行数统计:按换行符分割,处理结尾空行 let lineCount = content.split('\n').length; if (content.endsWith('\n')) { lineCount--; } // 渲染文件信息与行数 document.getElementById("details").innerHTML = ` <b>数据文件:</b> ${fileName} <br> <b>文件行数:</b> ${lineCount} <br> <br> <input type="submit" id="submit" value="确认上传"/> `; document.getElementsByClassName("confirm")[0].style.display = "block"; }; // 以文本格式读取文件 reader.readAsText(file); }
进阶说明(处理复杂CSV)
如果CSV存在带引号的多行单元格(比如单元格内包含换行符),基础统计会出错,可替换成以下严谨的统计逻辑:
function countCSVLines(content) { let lineCount = 1; let inQuotes = false; for (let char of content) { if (char === '"') { inQuotes = !inQuotes; } else if (char === '\n' && !inQuotes) { lineCount++; } } // 处理结尾空行 if (content.endsWith('\n') && !inQuotes) { lineCount--; } return lineCount; }
只需把原代码中lineCount的计算替换为const lineCount = countCSVLines(content);即可。
与现有Multer逻辑兼容
该前端统计逻辑完全独立于后端Multer上传流程,用户点击「确认上传」后,仍可通过原有表单提交或AJAX方式将文件发送至Express服务器,Multer的后端处理代码无需修改。
内容的提问来源于stack exchange,提问作者Ankita Basu
相关产品推荐
相关产品推荐

