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: