Friday 28 March 2014

How to increase or restrict the size of file upload in ASP.NET


In this article I will explain how to increase or restrict the size of file upload in ASP.NET

Syntax:

<httpRuntime
   executionTimeout = "HH:MM:SS"
   maxRequestLength = "number" />

Example:

Open your Web.config file, and just below the <system.web> tag, add the following tag:
Below code is useful for upload 20 MB size file.

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



Attributes :

ExecutionTimeout:

Optional TimeSpan attribute.
Specifies the maximum number of seconds that a request is allowed to execute before being automatically shut down by ASP.NET.
This time-out applies only if the debug attribute in the compilation element is False. To help to prevent shutting down the application while you are debugging, do not set this time-out to a large value.
The default is "00:01:50" (110 seconds).

maxRequestLength:

Specifies the limit for the input stream buffering threshold, in KB. This limit can be used to prevent denial of service attacks that are caused, for example, by users posting large files to the server.
The default is 4096 (4 MB).

Total Code:

We need to design aspx page. Below is the sample code for Page design.

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Check File Size</title>
</head>
<body>
<form id="form1" runat="server">
<table>
<tr>
<td> Check File size : <asp:FileUpload ID="fuCheck" runat="server" /></td>
</tr>
<tr>
<td> <asp:Button ID="btnCheckFileLenth" runat="server" Text="Check File Length" OnClick="btnCheckFileLenth_Click" /></td>
</tr>
<tr>
<td>
<asp:Label ID="lblMessage" runat="server" Text="Label"></asp:Label>
</td>
</tr>
</table>
</form>
</body>
</html>

Below is the sample code for checking File size code.

protected void btnCheckFileLenth_Click(object sender, EventArgs e)
{
if (fuCheck.HasFile)
{
// Here we can check the file file 20 mb are more
if (fuCheck.PostedFile.ContentLength < 20728650)
{
try
{
lblMessage.Text = "File name: " +
fuCheck.PostedFile.FileName + "<br>" +
fuCheck.PostedFile.ContentLength + " kb<br>" +
"Content type: " +
fuCheck.PostedFile.ContentType;
}
catch (Exception ex)
{
lblMessage.Text = "ERROR: " + ex.Message.ToString();
}
}
else
{
lblMessage.Text = "File size exceeds maximum limit 20 MB.";
}
}
}

No comments:

Post a Comment