I'm developing a website in Asp.Net and one of the page requires users to upload files. The client wants the file size limit to be set to 5MB max. I have set the limit in the web.config
using the following code;
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="5242880" /> <!--5MB-->
</requestFiltering>
</security> </system.webServer>
The C# code for the page to check the file extension and display the error message to the users has the following code.
string[] validFileTypes = { "doc", "docx", "xls", "pdf" };
string ext = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName);
bool isValidFile = false;
for (int i = 0; i < validFileTypes.Length; i++)
{
if (ext == "." + validFileTypes[i])
{
isValidFile = true;
break;
}
}
if (!isValidFile)
{
DisplayMessage.Visible = true;
DisplayMessage.Text = "Invalid file or file size has exceeded it max limit of 5MB. Please upload a file with one of the following extension; <br /><br />" +
string.Join(", ", validFileTypes) + "or a smaller file";
}
else
{
string targetFolder = HttpContext.Current.Server.MapPath("~/App_Data/");
string targetPath = Path.Combine(targetFolder, FileUpload1.FileName);
FileUpload1.SaveAs(targetPath);
DisplayMessage.Visible = true;
DisplayMessage.Text = "File uploaded successfully.";
}
The issue I am having is when I try to upload a file which is bigger than 5MB instead of the page displaying the error message it throws me a stack trace
Can someone please tell me where I'm going wrong. Many Thanks in advance!