FileUpload how to use Javascript to check whether the extension is effective

Source: Internet
Author: User

Common check methods. First, define a valid file extension and store it in the array.

Obtain the file path of the FileUpload control in JavaScript and obtain the file extension in the path. Compare it with the extension in the array. If yes, the uploaded file is valid. Otherwise, the file is invalid.

Copy codeThe Code is as follows: <asp: FileUpload ID = "FileUpload1" runat = "server"/>
<Asp: Button ID = "btnUpload" runat = "server" Text = "Upload" OnClientClick = "return ValidateFile ()"/>

The above HTML Button has an OnClientClick event, which is a JavaScript script method:Copy codeThe Code is as follows: <script type = "text/javascript">
Var validFilesTypes = ["png", "jpg", "jpeg", "gif"];

Function ValidateFile (){
Var file = document. getElementById ("<% = FileUpload1.ClientID %> ");
Var filePath = file. value;
Var ext = filePath. substring (filePath. lastIndexOf (".") + 1, filePath. length). toLowerCase ();

Var isValidFile = false;
For (var I = 0; I <validFilesTypes. length; I ++ ){
If (ext = validFilesTypes [I]) {
IsValidFile = true;
Break;
}
}

If (! IsValidFile ){
Alert ("invalid file. Upload the file with the extension \ n "+ validFilesTypes. join (","));
}

Return isValidFile;
}
</Script>

Demo:

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.