js判斷檔案型別大小並給出提示
阿新 • • 發佈:2022-04-29
上傳檔案是工作中常用的功能,不同的場景對不同的檔案型別和檔案大小都有不同的要求:
<form id="uploadForm" method="post" class="layui-form"> <div class="layui-form-item"> <label class="layui-form-label">名稱</label> <div class="layui-input-block"> <input type="text" name="name" required lay-verify="required" placeholder="請輸入檔名" autocomplete="off" class="layui-input"> </div> </div> <div class="layui-form-item"> <label class="layui-form-label">資料型別:</label> <div class="layui-input-block"> <select name="datatypeid" id="datatypeid"></select> </div> <input type="hidden" id="yincang"> </div> <div class="layui-form-item"> <label class="layui-form-label">上傳檔案</label> <div class="layui-input-block"> <input class="layui-input" type="file" name="file" onchange="fileChange(this);"/> </div> </div> <div class="layui-form-item"> <div class="layui-input-block"> <input type="button" class="layui-btn" value="上傳" onclick="upload()" /> </div> </div> </form>
js方法:
<script type="text/javascript"> var isIE = /msie/i.test(navigator.userAgent) && !window.opera; function fileChange(target, id) { var fileSize = 0; var filetypes = [ ".doc", ".docx" ];//這裡設定接受的檔案型別 var filepath = target.value; var filemaxsize = 1024 * 10;//接受的檔案最大10M if (filepath) { var isnext = false; var fileend = filepath.substring(filepath.indexOf(".")); if (filetypes && filetypes.length > 0) { for (var i = 0; i < filetypes.length; i++) { if (filetypes[i] == fileend) { isnext = true; break; } } } if (!isnext) { alert("不接受此檔案型別!"); target.value = ""; return false; } } else { return false; } if (isIE && !target.files) { var filePath = target.value; var fileSystem = new ActiveXObject("Scripting.FileSystemObject"); if (!fileSystem.FileExists(filePath)) { alert("附件不存在,請重新輸入!"); return false; } var file = fileSystem.GetFile(filePath); fileSize = file.Size; } else { fileSize = target.files[0].size; } var size = fileSize / 1024; if (size > filemaxsize) { alert("附件大小不能大於" + filemaxsize / 1024 + "M!"); target.value = ""; return false; } if (size <= 0) { alert("附件大小不能為0M!"); target.value = ""; return false; } } </script>