Wednesday, October 18, 2017

FileUpload Control File Type and File Size Validations

Normally we need validation to restrict the user for uploading any kind of files on a Web Server due to security or application requirement also we need to limit the file size to upload on web server.There are many ways to implement validation on file upload control its depend upon application requirement which method you can used .Here I will explain only three validation method you can implement on file upload controls.
 

Upload Control

Validation using Custom Validator on Client Side

You can used custom validator to implement fileupload validation on client side.This validation is faster and easy to implement. 
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">

    <script language="javascript" type="text/javascript">
        function ValidateAttachment(Source, args)
        {
          var UploadControl = document.getElementById('<%= UploadControl.ClientID %>'); 
          
          var FilePath = UploadControl.value;
         
          if(FilePath =='') 
          {            
            args.IsValid = false;//No file found
          }
          else
          {
            var Extension = FilePath.substring(FilePath.lastIndexOf('.') + 1).toLowerCase();
         
            if (Extension == "doc" || Extension == "txt")
            {
              args.IsValid = true; // Valid file type
            }
            else
            {
              args.IsValid = false; // Not valid file type
            }
           }
        }


    </script>

    <div>
        <asp:FileUpload ID="UploadControl" runat="server" />
        &nbsp;<asp:Button ID="btnUpload" runat="server" Text="Upload" 
            onclick="btnUpload_Click" style="height: 26px" />
        <br />
        <asp:CustomValidator ID="CustomValidator1" runat="server" ClientValidationFunction="ValidateAttachment"
            ErrorMessage="Please select valid .doc or .txt file" 
            onservervalidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
        <asp:Label runat="server" ID="StatusLabel" Text="Upload status: " />
       
    </div>
    </form>
</body>
</html>

Validation using Custom Validator on Server Side

You can also apply validation on server using custom validator its slower than client side but its more secure than client side. 

 protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
    {

        string UploadFileName = UploadControl.PostedFile.FileName;

        if (string.IsNullOrEmpty(UploadFileName))
        {
            args.IsValid = false;
        }
        else
        {
            string Extension = UploadFileName.Substring(UploadFileName.LastIndexOf('.') + 1).ToLower();

            if (Extension == "doc" || Extension == "txt")
            {
                if (UploadControl.PostedFile.ContentLength < 102400)
                {
                    args.IsValid = true;

                }
                else
                {
                    args.IsValid = false;
                    CustomValidator1.ErrorMessage = "File size should be less than 100 kb";
                }
            }
            else
            {
                args.IsValid = false; // Not valid file type
                CustomValidator1.ErrorMessage = "File Type should be .doc or .txt";
            }
        }



    }

By default, the maximum size of a file to be uploaded to the server using the FileUpload control is around 4MB. You cannot upload anything that is larger than this limit. 




Change File Upload Limit


In the web.config file, find a node called <httpRuntime> that looks like the following: 

<httpRuntime 
executionTimeout="110" 
maxRequestLength="4096" 
requestLengthDiskThreshold="80" 
useFullyQualifiedRedirectUrl="false" 
minFreeThreads="8" 
minLocalRequestFreeThreads="4" 
appRequestQueueLimit="5000" 
enableKernelOutputCache="true" 
enableVersionHeader="true" 
requireRootedSaveAsPath="true" 
enable="true" 
shutdownTimeout="90" 
delayNotificationTimeout="5" 
waitChangeNotification="0" 
maxWaitChangeNotification="0" 
enableHeaderChecking="true" 
sendCacheControlHeader="true" 
apartmentThreading="false" />



lot is going on in this single node, but the setting that takes care of the size of the files to be uploaded is the maxRequestLength attribute. By default, this is set to 4096 kilobytes (KB). Simply change this value to increase the size of the files that you can upload to the server. If you want to allow 10 megabyte (MB) files to be uploaded to the server, set the maxRequestLength value to 11264, meaning that the application allows files that are up to 11000 KB to be uploaded to the server.


for futher detail check this Working Around File Size Limitations.


Direct Validation on Upload Button 


In this method you don’t need to used custom validator you can directly write the code on button click and manually show message using label control.


 protected void btnUpload_Click(object sender, EventArgs e)
    {

        if (UploadControl.HasFile)
        {
            try
            {
                if (UploadControl.PostedFile.ContentType == "image/jpeg")
                {
                    if (UploadControl.PostedFile.ContentLength < 102400)
                    {
                        string filename = Path.GetFileName(UploadControl.FileName);
                        UploadControl.SaveAs(Server.MapPath("~/") + filename);
                        StatusLabel.Text = "Upload status: File uploaded!";
                    }
                    else
                        StatusLabel.Text = "Upload status: The file has to be less than 100 kb!";
                }
                else
                    StatusLabel.Text = "Upload status: Only .doc or .txt files are accepted!";
            }
            catch (Exception ex)
            {
                StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
            }
        }

    }

source : https://dotnetfarrukhabbas.blogspot.com/2011/08/fileupload-control-file-type-and-file.html

No comments:

Post a Comment