In this article I will explain with an example, how to filter files based on extensions in ASP.Net FileUpload control.
When a file is selected in the FileUpload control, the extension of the selected file will be validated using
JavaScript and Custom Validator.
HTML Markup
The HTML Markup consists of:
FileUpload – For selecting file.
Button – For uploading file.
CustomValidator – For validating and displaying appropriate message.
The
CustomValidator control has been assigned with
ClientValidationFunction which is set to
ValidateFile JavaScript function.
<asp:FileUpload ID="fuUpload" runat="server" />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" />
<br/>
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="" ForeColor="Red"
ControlToValidate="fuUpload" ClientValidationFunction="ValidateFile" />
Validating File using CustomValidator with JavaScript
When file is selected,
ValidateFile JavaScript function is called.
Inside the
ValidateFile JavaScript function, the file extension of the uploaded file is determined and an Array of valid file type is defined.
Then, the file extension is verified whether exists or not in the Array using the Array.includes function and returned value is set in IsValid argument.
The following Array can be easily set with valid file extensions as per your requirement.
var validFilesTypes = ["doc", "docx", "pdf"];
Finally, if the IsValid argument is false, then error message is set in the Custom Validator.
<script type="text/javascript">
function ValidateFile(sender, args) {
sender.innerHTML = "";
var filePath = document.getElementById(sender.controltovalidate).value;
var extension = filePath.substring(filePath.lastIndexOf(".") + 1, filePath.length).toLowerCase();
var validFilesTypes = ["doc", "docx", "pdf"];
args.IsValid = validFilesTypes.includes(extension);
if (!args.IsValid) {
sender.innerHTML = "Invalid File. Please upload file with extension: " + validFilesTypes.join(", ") + ".";
}
}
</script>
Screenshot
Browser Compatibility
* All browser logos displayed above are property of their respective owners.
Demo
Downloads