# Jquery 驗證檔案大小和格式 **html:** ```javascript=\ <input type="file" size="60" name="uploads" > ``` **script:** ```javascript=\ //檢查檔案大小 function checkFileSize(totalSize) { var SizeLimit = 5242880; //上傳上限5120KB(5MB),單位:byte if (totalSize > SizeLimit) { var msg = "已超過單次上傳上限 "+(SizeLimit /1024) + " KB\n不允許上傳!"; alert(msg); return true; } else { return false; } } //檢查檔案格式 function checkFileType(fileType){ if(fileType != "text/plain"){ alert("檔案格式不符合txt檔!!") return true; }else{ return false; } } //檢查上傳檔案格式和大小 $('input[name=uploads]').change(function() { var file = this.files[0]; //定義file=發生改的file name = file.name; //name=檔案名稱 size = file.size; //size=檔案大小 type = file.type; //type=檔案型態 if(checkFileSize(size)) { //檢查檔案大小 $(this).val(""); //將檔案欄設為空白 } else if(checkFileType(type)) { //檢查檔案格式 $(this).val(""); //將檔案欄設為空 } }); ``` ###### tags: `JQuery`
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up