Home > ASP.Net > Validate Uploaded File Size and Extensions

Validate Uploaded File Size and Extensions


Hi all,

in my previous posts i provided examples how to validate Uploaded file size and extenstions

JQuery to Validate File Upload Extension

Custom Validator to Validate FileUpload Extension

Validate FileUpload Extension

Validate Fileupload Control

Validate Size of Uploaded Images

Validate uploaded Image Hieght and Width

Validate FileUpload Size

Use JQuery with FileUpload

AJAX AsynFile Upload with File Extension Validation

Allow User to Upload only .doc file

 

In this example i will show how to validate uploaded file size and extenstions

1) Open VS2010 and create a new website

2) Add Web.Config file and in AppSettings sction add the following lines


<appSettings>
 <clear />
 <add key="AllowedFileExtension" value="jpeg,jpg,tiff,tif,png,bmp"/>
 <add key="MaxFileSize" value="524288"/>
 <add key="UploadedFiles" value="~/UploadedFiles/" />
 </appSettings>

3) Add new web page and from toolbox drag and drop ASP.NET FileUpload and Button controls


<script type="text/javascript">
 function UploadFileCheck(source, arguments) {
 // Works only With IE explorer
 if (navigator.userAgent.toLowerCase().indexOf('msie') > -1)
 { }
 else {
 var iSize = $(".fileupload")[0].files[0].size;
 var MaxSize = '<%=ConfigurationManager.AppSettings["MaxFileSize"].ToString() %>';
 var MaxSizeKb = parseInt(MaxSize / 1024);
 if (iSize > MaxSize) {
 alert('File size should not exceed ' + MaxSizeKb + ' Kb');
 arguments.IsValid = false;
 //return;
 }
 }

var sFile = arguments.Value.toLowerCase();
 var AllowedExtensions = '<%=ConfigurationManager.AppSettings["AllowedFileExtension"].ToString() %>';
 var extenstions = AllowedExtensions.split(',');
 //alert(extenstions[0]);
 var i;
 var ext = false;
 for (i = 0; i < extenstions.length; i++) {
 if (sFile.endsWith('.' + extenstions[i].toLowerCase())) {
 ext = true;
 break;
 }
 }
 if (!ext) {
 alert('Allowed extensions ' + AllowedExtensions );
 }
 arguments.IsValid = ext;
 }
 function showWait() {
 if ($get('myFile').value.length > 0) {
 $get('UpdateProgress1').style.display = 'block';
 }
 }
</script>
<table style="width: 100%">
 <tr>
 <td class="txtright">&nbsp;</td>
 <td class="txtright">&nbsp;</td>
 <td class="txtright">&nbsp;</td>
 <td class="txtright">&nbsp;</td>
 <td class="txtright">&nbsp;</td>
 <td class="txtright">&nbsp;</td>
 </tr>
 <tr>
 <td colspan="6">
 <asp:Label ID="Label1" runat="server" Text="Upload File" Font-Size="Medium" Font-Names="Tahoma" ForeColor="#5C9462" Font-Bold="true"></asp:Label>
 </td>
 </tr>
</table>
<table style="width: 100%" id="tblNewUpload" runat="server">
 <tr>
 <td>&nbsp;</td>
 <td class="txtright">&nbsp;</td>
 <td>&nbsp;</td>
 <td class="txtright">&nbsp;</td>
 <td>&nbsp;</td>
 <td class="txtright">&nbsp;</td>
 </tr>
 <tr>
 <td class="txtright">
 <asp:Label ID="lblFile" runat="server" Text="File"></asp:Label>
 </td>
 <td class="txtright">
 <asp:FileUpload ID="myFile" runat="server" CssClass="fileupload"></asp:FileUpload>
 <asp:CustomValidator ID="cvmyFile" ForeColor="Red" runat="server" ClientValidationFunction="UploadFileCheck" ControlToValidate="myFile" ErrorMessage="CustomValidator" SetFocusOnError="True" ValidationGroup="Upload" Display="Dynamic">*</asp:CustomValidator>
 <asp:RequiredFieldValidator ID="rfvmyFile" ForeColor="Red" runat="server" ControlToValidate="myFile" Display="Dynamic" ErrorMessage="RequiredFieldValidator" SetFocusOnError="True" ValidationGroup="Upload">*</asp:RequiredFieldValidator>
 </td>
 <td class="txtright">
 <asp:Button ID="btnUpload" runat="server" Text="Upload File" OnClick="btnUpload_Click" ValidationGroup="Upload" />
 </td>
 <td class="txtright">
 <asp:Label ID="lblMsg" runat="server" ></asp:Label>
 </td>
 <td>&nbsp;</td>
 <td class="txtright">&nbsp;</td>
 </tr>
 <tr>
 <td style="text-align:center" colspan="6">
 <asp:Label ID="lblTypes" runat="server" ForeColor="Red" Font-Size="12px" Font-Bold="False"></asp:Label>
 </td>
 </tr>
</table>

4) In Code behind add the following code :


public string UploadFolder
 {
 get
 {
 String s = (String)ViewState["UploadFolder"];
 return ((s == null) ? ConfigurationManager.AppSettings["UploadedFiles"].ToString() : s);
 }
 set
 {
 ViewState["UploadFolder"] = value;
 }
 }

private string getExtension(string contenttype)
 {
 if (contenttype == "application/vnd.openxmlformats-officedocument.wordprocessingml.document")
 {
 return "docx";
 }
 else if (contenttype == "application/msword")
 {
 return "doc";
 }
 else if (contenttype == "application/pdf")
 {
 return "pdf";
 }
 else if (contenttype == "image/jpeg")
 {
 return "jpg";
 }
 else if (contenttype == "image/gif")
 {
 return "gif";
 }
 else if (contenttype == "image/jpeg")
 {
 return "jpeg";
 }
 else if (contenttype == "image/pjpeg")
 {
 return "jpeg";
 }
 else if (contenttype == "image/png")
 {
 return "png";
 }
 else if (contenttype == "image/tiff")
 {
 return "tiff";
 }
 else if (contenttype == "image/tif")
 {
 return "tif";
 }
 else
 {
 return "unknown";
 }
 }

protected void Page_Load(object sender, EventArgs e)
 {
 if (!IsPostBack)
 {
 lblTypes.Text = " Allowed Extensions " + ConfigurationManager.AppSettings["AllowedFileExtension"] + " Only ";
 }
 }

protected void btnUpload_Click(object sender, EventArgs e)
 {
 try
 {
 if (myFile.HasFile)
 {
 string _allowedExtensions = ConfigurationManager.AppSettings["AllowedFileExtension"].ToString();
 int MaxFileSize = int.Parse(ConfigurationManager.AppSettings["MaxFileSize"].ToString());
 string[] _values = _allowedExtensions.Split(',');
 string fileExtension = Path.GetExtension(myFile.FileName).ToLower();
 int fileSize = myFile.PostedFile.ContentLength;
 if (_values.Where(x => x == fileExtension.Replace(".", "")).Count() > 0)
 {
 //-- Check file Size
 if (fileSize > MaxFileSize)
 {
 throw new BusinessErrors("ER0174", Convert.ToInt32(MaxFileSize / 1024).ToString()); // File Size is not Allowed
 }

//-- Check File Extension With Content Type
 string content_type = myFile.PostedFile.ContentType;
 string content_extension = getExtension(content_type);
 if (_values.Where(x => x == content_extension).Count() <= 0)
 {
 throw new BusinessErrors("ER0173"); // File Extension is not allowed
 }

try
 {
 System.Drawing.Image image = System.Drawing.Image.FromStream(myFile.FileContent);
 string FormetType = string.Empty;
 if (image.RawFormat.Guid == System.Drawing.Imaging.ImageFormat.Tiff.Guid)
 FormetType = "TIFF";
 else if (image.RawFormat.Guid == System.Drawing.Imaging.ImageFormat.Gif.Guid)
 FormetType = "GIF";
 else if (image.RawFormat.Guid == System.Drawing.Imaging.ImageFormat.Jpeg.Guid)
 FormetType = "JPG";
 else if (image.RawFormat.Guid == System.Drawing.Imaging.ImageFormat.Bmp.Guid)
 FormetType = "BMP";
 else if (image.RawFormat.Guid == System.Drawing.Imaging.ImageFormat.Png.Guid)
 FormetType = "PNG";
 else
 throw new BusinessErrors("ER0173"); // File Extension is not allowed
 }
 catch (System.ArgumentException exp)
 {
 throw new BusinessErrors("ER0173"); // File Extension is not allowed
 }

 string fileName;
 fileName = Guid.NewGuid().ToString() + Path.GetExtension(myFile.FileName);
 myFile.PostedFile.SaveAs(Server.MapPath(UploadFolder + fileName));
 ((BasePage)this.Page).DisplayMessage("ER0035"); // File Uploaded
 }
 else
 {
 throw new BusinessErrors("ER0173"); // File Extension is not allowed
 }
 }
 else
 {
 ((BasePage)this.Page).DisplayErrorMessage("ER0094"); // Please select a file
 }
 }
 catch (ALLOWANCES.Common.BusinessErrors ex)
 {
 ((BasePage)this.Page).DisplayErrorMessage(ex.Message);
 }
 catch (Exception ex)
 {
 ((BasePage)this.Page).DisplayErrorMessage("ER0115"); // Error
 }
 }
 }

Hope this helps

Good Luck.

Advertisements
Categories: ASP.Net
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: