js前端验证上传的文件大小及格式
js前端验证上传的文件大小及格式
<script type="text/javascript"> function fileChange(target) { var fileSize = 0; if (!target.files) { var filePath = target.value; var fileSystem = new ActiveXObject("Scripting.FileSystemObject"); var file = fileSystem.GetFile(filePath); fileSize = file.Size; } else { fileSize = target.files[0].size; } var size = fileSize / 1024; if (size <110) { //空白的Excel表最大为10.1KB,当小于它及判断为Excel内容为空 alert("导入的Excel表不能为空!"); target.value = ""; return } if (size > 5000) { alert("导入的Excel表不能大于5M!"); target.value = ""; return } var name = target.value; var fileName = name.substring(name.lastIndexOf(".") + 1).toLowerCase(); if (fileName != "xlsx" && fileName != "xls") { alert("请选择.xlsx格式文件上传!"); target.value = ""; return } } </script>
调用JS的input框
<td><input type="file" id="file" name="file" accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" onchange="fileChange(this);"></td>