Js sample code used to determine the type and size of the uploaded file

Source: Internet
Author: User

Copy codeThe Code is as follows:
// Check the file size and type
Function fileChange (target ){
// Check the type of the uploaded file
If (! (/(? : Jpg | gif | png | jpeg) $/I. test (target. value ))){
Alert ("only jpg files can be uploaded | gif | png | jpeg images ");
If (window. ActiveXObject) {// for IE
Target. select (); // select the file, and clear selection
Document. selection. clear ();
} Else if (window. opera) {// for opera
Target. type = "text"; target. type = "file ";
} Else target. value = ""; // for FF, Chrome, Safari
Return;
} Else {
Return; // alert ("OK"); // or you can do nothing here.
}

// Check the size of the uploaded file
Var isIE =/msie/I. test (navigator. userAgent )&&! Window. opera;
Var fileSize = 0;
If (isIE &&! 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 & gt; (500 )){
Alert ("the file size cannot exceed 500KB ");
If (window. ActiveXObject) {// for IE
Target. select (); // select the file, and clear selection
Document. selection. clear ();
} Else if (window. opera) {// for opera
Target. type = "text"; target. type = "file ";
} Else {
Target. value = ""; // for FF, Chrome, Safari
}
Return;
} Else {
Return;
}
}

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.