The client js determines the file type and file size, that is, the size of the upload is limited.

Source: Internet
Author: User

Due to project needs! The script is required to determine the size and file type on the client! I have worked hard to find information on the Internet! Simply write an example and test the file upload size limit. compatible with browsers such as ie6, ie7, ie8, Google Chrome, and ff.
Copy codeThe Code is as follows:
<Html>
<Head>
<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; // 2 M
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 ("this file type is not accepted! ");
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 ("the attachment does not exist. Please enter it again! ");
Return false;
}
Var file = fileSystem. GetFile (filePath );
FileSize = file. Size;
} Else {
FileSize = target. files [0]. size;
}

Var size = fileSize/1024;
If (size> filemaxsize ){
Alert ("the attachment size cannot be greater than" + filemaxsize/1024 + "M! ");
Target. value = "";
Return false;
}
If (size <= 0 ){
Alert ("the attachment size cannot be 0 MB! ");
Target. value = "";
Return false;
}
}
</Script>
</Head>
<Body>
<Input type = "file" name = "contractFileName" style = "width: 500px;" onchange = "fileChange (this);"/>
</Body>
</Html>

Related Article

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.