Client JS determine file type and file size that is, limit upload size _javascript tips

Source: Internet
Author: User
Because the project needs! Need script to judge size and file type on client! I find information on the Internet to find a good hard work! Simply write yourself a and test file upload size limit An example, compatible with IE6,IE7,IE8, Google Chrome,ff and other browsers
Copy Code code as follows:

<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/>
<script type= "Text/javascript" >
var Isie =/msie/i.test (navigator.useragent) &&!window.opera;
function Filechange (target,id) {
var fileSize = 0;
var filetypes =[". jpg", ". png", ". rar", "TXT", ". zip", ". Doc", ". ppt", ". xls", ". pdf", ". docx", ". xlsx"];
var filepath = Target.value;
var filemaxsize = 1024*2;//2m
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 ("Does not accept this file type!") ");
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 ("Attachment does not exist, please re-enter!") ");
return false;
}
var file = Filesystem.getfile (FilePath);
fileSize = file. Size;
} else {
FileSize = target.files[0].size;
}

var size = filesize/1024;
if (size>filemaxsize) {
Alert ("Attachment size cannot be greater than" +filemaxsize/1024+ "M!) ");
Target.value = "";
return false;
}
if (size<=0) {
Alert ("Attachment size cannot be 0m! ");
Target.value = "";
return false;
}
}
</script>
<body>
<input type= "File" Name= "Contractfilename" style= "width:500px" onchange= "Filechange" (this); " />
</body>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.