Validating the size of a Uploaded File

Most often, in our websites, we will be required to validate the end user's uploaded file size. This is how to do it.

1. Add the File upload control to the aspx page



< asp:FileUpload ID="objFileUpload" runat="server" ToolTip="UpLoad Your Files" Width="230px" />



2. In the web.config, specify the maximum valid file size in KB


< appSettings>
< add key="MaxFileSize" value="10240"/>
</appSettings>


3. In the file upload page, get the MaxFileSize in a double variable



double dblMaxFileSize = Convert.ToDouble(ConfigurationManager.AppSettings["MaxFileSize"]);



4. Get the size of the file.



int intFileSize = fupIcon.PostedFile.ContentLength; // Here the file size is obtained in bytes
double dblFileSizeinKB = intFileSize / 1024.0; // We convert the file size into kilobytes



5. Check if the uploaded file size is greater than the set Max limit



if ((dblFileSizeinKB > dblMaxFileSize ))
{
lblMsg.Text = "File Size Should be less than" + dblMaxFileSize.ToString() + " KB";
return;
}


Comments

Author: ABitSmart30 Jan 2010 Member Level: Gold   Points : 0

Please format your resource.

Author: Antony Vasanth Kani30 Jan 2010 Member Level: Gold   Points : 0

Hi Abitsmart, I have reformatted the resource.

Author: Saurabh Pandey18 Feb 2010 Member Level: Silver   Points : 1

if i have two upload controls and each have different size validation, then how will it works?
one control for .mp3 (2MB) and one for .jpg(1024KB)?

Author: Antony Vasanth Kani22 Feb 2010 Member Level: Gold   Points : 2

Hi,

It is just the same, you will have to make some alterations to the existing code

In the 2nd point



<add key="MaxFileSizeMP3" value="20480"/>
<add key="MaxFileSizeJPG" value="10240"/>



In the code behind, check for individual file size and alert as necessary

Author: asdfg23 Feb 2010 Member Level: Gold   Points : 1

int size = FileUpload1.PostedFile.ContentLength;
returns integer value in Bytes....
u can use this value before
FileUpload1.SaveAs() method

Author: Developer25 Feb 2010 Member Level: Gold   Points : 1

using this also we can upload

protected void btn1_Click(object sender, EventArgs e)
{
string path = Server.MapPath("./Files");
path += "/" + fileupload1.FileName;
lbl1.Text = path;
fileupload1.SaveAs(path);
}



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: