Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I Validate the File Type of a File Upload?

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).

like image 773
Yaakov Ellis Avatar asked Sep 16 '08 13:09

Yaakov Ellis


People also ask

How do I validate a file type upload?

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.

How do I verify a file type?

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.

What is a validation file?

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.


1 Answers

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;       } } 
like image 108
Jamie Avatar answered Sep 25 '22 15:09

Jamie