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).
It's pretty simple using regulare expression validator.
Client-Side Validation of File Types Permissible to Upload
As an alternative option, could you use the "accept" attribute of HTML File Input which defines which MIME types are acceptable.
Definition here
I think there are different ways to do this. Since im not familiar with asp i can only give you some hints to check for a specific filetype:
1) the safe way: get more informations about the header of the filetype you wish to pass. parse the uploaded file and compare the headers
2) the quick way: split the name of the file into two pieces -> name of the file and the ending of the file. check out the ending of the file and compare it to the filetype you want to allow to be uploaded
hope it helps :)
As some people have mentioned, Javascript is the way to go. Bear in mind that the "validation" here is only by file extension, it won't validate that the file is a real excel spreadsheet!
You could use a regular expression validator on the upload control:
There is also the accept attribute of the input tag:
but I did not have much success when I tried this (with FF3 and IE7)
Well - you won't be able to do it server-side on post-back as the file will get submitted (uploaded) during the post-back.
I think you may be able to do it on the client using JavaScript. Personally, I use a third party component called radUpload by Telerik. It has a good client-side and server-side API, and it provides a progress bar for big file uploads.
I'm sure there are open source solutions available, too.