Search This Blog

Tuesday, January 25, 2011

How to restrict size of file upload in asp.net


I have one page that contains one file upload control to accept files from user and saving it in one folder. I have written code to upload file and saving it to folder it’s working fine after completion of my application my friend has tested my application like he uploaded large size file nearly 10 MB file at that time it’s shown the error page like “the page cannot displayed”. 

Again I have search in net I found that file upload control allows maximum file size is 4MB for that reason if we upload file size larger than 4MB we will get error page like “the page cannot displayed” or “Maximum request length exceeded”.

After that I tried to increase the size of uploaded file by setting some properties in web.config 
file like this 


<system.web>
<httpRuntime executionTimeout="9999" maxRequestLength="2097151"/>
</system.web>


Here httpRuntime means

Configures ASP.NET HTTP runtime settings. This section can be declared at the machine, site, application, and subdirectory levels.

executionTimeout means

Indicates the maximum number of seconds that a request is allowed to execute before being automatically shut down by ASP.NET.

maxRequestLength means

Indicates the maximum file upload size supported by ASP.NET. This limit can be used to prevent denial of service attacks caused by users posting large files to the server. The size specified is in kilobytes. The default is 4096 KB (4 MB).

After that write the following code in aspx page

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="FileUpload1" runat="server" />
<br />
<asp:Button ID="btnUpload" runat="server" Text="Upload" onclick="btnUpload_Click" />
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>
</html>

After that write the following code in code behind


protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
if (FileUpload1.PostedFile.ContentLength < 20728650)
{
try
{
Label1.Text = "File name: " +
FileUpload1.PostedFile.FileName + "<br>" +
FileUpload1.PostedFile.ContentLength + " kb<br>" +
"Content type: " +
FileUpload1.PostedFile.ContentType;
}
catch (Exception ex)
{
Label1.Text = "ERROR: " + ex.Message.ToString();
}
else
{
Label1.Text = "File size exceeds maximum limit 20 MB.";
}
}
}


After that write the following code in web.config

<system.web>
<httpRuntime executionTimeout="9999" maxRequestLength="2097151"/>
</system.web>

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.