Monday, September 10, 2012

Upload Large Files in ASP.NET

ASP.Net have set the restrictions to upload the file to the server of only 4 MB by default. We can increase this setting in Web.Config through the <httpRuntime> tag.
To upload large files in asp.net, you need change some default parameters and add tags in your configuration file, i.e. Web.Config inside <System.Web> tag.
Check out the following configuration for web.config

<httpRuntime 
maxRequestLength="4096"  
shutdownTimeout="90" 
executionTimeout="110"  
requestLengthDiskThreshold="80"
useFullyQualifiedRedirectUrl="false"  
minFreeThreads="8"  
minLocalRequestFreeThreads="4"
appRequestQueueLimit="5000"           
enableKernelOutputCache="true" 
enableVersionHeader="true"
 requireRootedSaveAsPath="true"    
enable="true"  

delayNotificationTimeout="5"                
waitChangeNotification="0"  
maxWaitChangeNotification="0"
enableHeaderChecking="true"  
sendCacheControlHeader="true"  
apartmentThreading="false" />


To increase the default upload size, we need to increase the value of maxRequestLength property to whatever we want in KB. Default is 4096 KB(4MB).

To upload 100 MB, set
maxRequestLength="102400"


Now to upload the file we need FileUpload control in .aspx file
 
<asp:FileUpload ID="UploadCtrl" runat="server" />

In code behind,

Step 1: Add following namespace 

            using System.IO;

Step 2: Declare global variable 

            String path = HttpContext.Current.Request.PhysicalApplicationPath + "images\\";
            Boolean FileOK = false;   // TO CHECK THE FILE TYPE
            Boolean FileSaved = false;

 Step 3: Add Upload function

private string uploadImage(FileUpload Upload)
        {
            string imgpath = null;
            try
            {
                if (Upload.HasFile)
                {
                    Session["WorkingImage"] = Upload.FileName;

                    String FileExtension = Path.GetExtension(Session["WorkingImage"].ToString()).ToLower();
                    String[] allowedExtensions = { ".png", ".jpeg", ".jpg", ".gif" };
                    for (int i = 0; i < allowedExtensions.Length; i++)
                    {
                        if (FileExtension == allowedExtensions[i])
                        {
                            FileOK = true;
                        }
                    }
                }
                if (FileOK)
                {
                    try
                    {
                        long str = System.DateTime.Now.ToBinary();
                        Session["WorkingImage"] = str.ToString() + Session["WorkingImage"];
                        Upload.PostedFile.SaveAs(path + Session["WorkingImage"]);
                        FileSaved = true;
                    }
                    catch (Exception ex)
                    {
                        message.Visible = true;
                        message.Attributes.Add("style", "margin-bottom: 5px");
                        message.Attributes.Add("id", "message-red");
                        messageClass.Attributes.Add("class", "red-left");
                        messageIcon.Src = "images/table/icon_close_red.gif";
                        lblresult.Text = "File could not be uploaded." + ex.Message.ToString();
                        lblresult.Visible = true;
                        FileSaved = false;
                    }
                }
                else
                {
                    message.Visible = true;
                    message.Attributes.Add("style", "margin-bottom: 5px");
                    message.Attributes.Add("id", "message-red");
                    messageClass.Attributes.Add("class", "red-left");
                    messageIcon.Src = "images/table/icon_close_red.gif";
                    lblresult.Text = "Cannot accept files of this type.";
                    lblresult.Visible = true;
                }
                if (FileSaved)
                {
                    Upload.Visible = false;
                    //imgContent.ImageUrl = "../images/" + Session["WorkingImage"].ToString();
                }
               
                if (FileOK)
                {
                    imgpath = "../images/" + Session["WorkingImage"].ToString();
                }
            }
            catch (Exception ex)
            {
                message.Visible = true;
                lblresult.Text = ex.Message;
                message.Attributes.Add("style", "margin-bottom: 5px");
                messageIcon.Src = "images/table/icon_close_red.gif";
                messageClass.Attributes.Add("class", "red-left");
            }
            return imgpath;
        }


Step 4:  Call Upload function.

You just need to pass your File upload  control ID to the function.

protected void btnSubmit_Click(object sender, EventArgs e)
{
      string FileNamePath = uploadImage(UploadCtrl);
}