Thursday, June 11, 2009

How to check file types when uploading file in ASP.NET

In order to upload a file in ASP.NET, we can use the FileUpload control. The FileUpload control is built-in in ASP.NET. FileUpload control meets the basic requirement of uploading file. However, this control has some limitations. For example, we cannot specify the type of the file that a user can upload. But we can easily create a Custom Validator to set the type of file that a user can upload. The following code snippet shows the custom validator:

public class FileUploadTypeValidator : CustomValidator
{
public FileUploadTypeValidator()
{
base.ErrorMessage = "pdf, doc, docx, xls, xlsx, and ppt files are allowed.";
base.Text = "*";
base.SetFocusOnError = true;
base.ToolTip = "pdf, doc, docx, xls, xlsx, and ppt files are allowed.";
base.ClientValidationFunction = "ClientValidateFileType";
this.FileTypes = "pdfPDFdocDOCdocxDOCXxlsXLSxlsxXLSXpptPPT";
}

protected override void OnInit(EventArgs e)
{
base.OnInit(e);
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), this.ClientID + "ADDScript", GetScript(), true);
}

protected override bool OnServerValidate(string value)
{
//return base.OnServerValidate(value);
FileUpload fu = this.Parent.FindControl(this.ControlToValidate) as FileUpload;
if (fu != null && !string.IsNullOrEmpty(fu.FileName))
{
string ext = System.IO.Path.GetExtension(fu.FileName);
string[] fileTypes = this.FileTypes.Split('');
foreach (string item in fileTypes)
{
if (!ext.Equals( "." + item))
{
return true;
}
}
}
return false;
}

public string FileTypes { get; set; }

private string GetScript()
{
string script = string.Empty;
script = @"function ClientValidateFileType(source, arguments) {"
+ " var FilePath = arguments.Value;"
+ " var Extension = FilePath.substring(FilePath.lastIndexOf('.') + 1).toLowerCase();"
+ " var exten = new Array();"
+ " exten = \"" + this.FileTypes + "\";"
+ " var extens = exten.split(\"\");"
+ " var isValid = false;"
+ " for (var i = 0; i < extens.length; i++) {"
+ " if (extens[i] == Extension) {"
+ " isValid = true;"
+ " break;"
+ " }"
+ " }"
+ " arguments.IsValid = isValid;"
+ " }";
return script;
}
}

The above code snippet checks the type of the in both the client and server side. In order to use this custom validator, use the following markup:




AELCtl is the tagprefix of the custom validator. You can set the type of files you want to allow by using the FileTypes property. The above validator allows jpg, jpeg and GIF files

Hope this help!

No comments: