0

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 enter image description here

Can someone please tell me where I'm going wrong. Many Thanks in advance!

Izzy
  • 6,740
  • 7
  • 40
  • 84

3 Answers3

1

write this in web.config file

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

// took a label(id= Label1) control to show error.

if (FileUpload1.HasFile)
{
   if (FileUpload1.PostedFile.ContentLength < 5242880)
     {
        /* your code */
      }
  else
    {
     Label1.Text = "File size exceeds maximum limit 5 MB.";
    }
}
Amit Kumar
  • 5,888
  • 11
  • 47
  • 85
  • Thanks for this. Worked perfectly with a little adjustment in the `web.config` file. – Izzy Aug 21 '14 at 10:28
0

Try the following solution from this SO answer

<configuration>
  <system.web>
    <httpRuntime maxRequestLength="xxx" />
  </system.web>
</configuration>

Additionally, you could do the validation client side if you wanted.

Community
  • 1
  • 1
  • Still the same stack trace – Izzy Aug 21 '14 at 09:12
  • Validation client side is only a HTML 5 solution. How many people build web sites that only the latest browsers can use? Most of my corporate clients are still on IE 8 or 9. – Martin Smellworse Aug 21 '14 at 10:10
  • A combination of both is ideal. I like to handle the upload size client side **if possible**. Depending on the size of the upload limit, this can be a better experience for the end user. If it's a 50mb limit, I'd rather get an alert right away rather than waiting 2 minutes for the file to finish uploading. – disappointed in SO leadership Aug 21 '14 at 18:08
0

fileId = ID of the file tag fileMsg = Id of the Div which is put below the File Input like

<html>
 <input type="file" id="fileId" name="file" onchange="uploadFile()">
 <div id="fileMsg"></div>



<script>
function uploadFile() {
    var filename = $('#fileId').val().split('.').pop().toLowerCase();
    var fileInput =  document.getElementById('fileId');
    if (filename == 'doc' || filename == 'xls' || filename == 'docx' || filename == 'pdf') {
        var filesize=(fileInput.files[0].size);
        if (filesize > 5000000) {
            $('#fileMsg').html('Invalid File Size');
        } else {
            $('#fileMsg').html('');
        }
    } else {
        $('#fileMsg').html('Invalid File Type');
    }
}
</script>
</html>