Kindly see code snippet below for validating if file submitted is a valid file type. As well as checking if a file was submitted to start with.
//Javascript
$("#btnUpload").click(function (e) {
var file = $("#fileupload").val(); //Fetch the filename of the submitted file
if (file == '') { //Check if a file was selected
//Place warning text below the upload control
$(".errorDiv").html("Please select a file first.");
e.preventDefault();
}
else {
//Check file extension
var ext = file.split('.').pop().toLowerCase(); //Check file extension if valid or expected
if ($.inArray(ext, ['txt']) == -1) {
$(".errorDiv").html("Select valid text file (txt).");
e.preventDefault(); //Prevent submission of form
}
else {
//Do your logic here, file upload, stream. etc.. if file was successfully validated
}
}
});
//For the HTML
<input id="fileupload" type="file" name="files[]" /><br />
<p class="reminder"> Allowed file type: .txt</p>
<div class="errorDiv"></div>
<input type="button" id="btnUpload" value="Upload File"/><br />
Heads up: Perform file validation on the server side as well to prevent back-end error or data injections.
I hope this helps!