I am using <input type="file" id="fileUpload" runat="server">
to upload a file in an ASP.NET application. I would like to limit the file type of the upload (example: limit to .xls or .xlsx file extensions).
Both JavaScript or server-side validation are OK (as long as the server side validation would take place before the files are being uploaded - there could be some very large files uploaded, so any validation needs to take place before the actual files are uploaded).
Using JavaScript, you can easily check the selected file extension with allowed file extensions and can restrict the user to upload only the allowed file types. For this we will use fileValidation() function. We will create fileValidation() function that contains the complete file type validation code.
Right-click the file. Select the Properties option. In the Properties window, similar to what is shown below, see the Type of file entry, which is the file type and extension.
The File Validation Agent solution determines whether the files associated with documents in a workspace are missing. It searches for those files on a file server. It sets the value of a Yes/No field called the missing files indicator field. The value in this field indicates whether the files were found.
Seems like you are going to have limited options since you want the check to occur before the upload. I think the best you are going to get is to use javascript to validate the extension of the file. You could build a hash of valid extensions and then look to see if the extension of the file being uploaded existed in the hash.
HTML:
<input type="file" name="FILENAME" size="20" onchange="check_extension(this.value,"upload");"/> <input type="submit" id="upload" name="upload" value="Attach" disabled="disabled" />
Javascript:
var hash = { 'xls' : 1, 'xlsx' : 1, }; function check_extension(filename,submitId) { var re = /\..+$/; var ext = filename.match(re); var submitEl = document.getElementById(submitId); if (hash[ext]) { submitEl.disabled = false; return true; } else { alert("Invalid filename, please select another file"); submitEl.disabled = true; return false; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With