0

I am trying to control size of my picture to do not be more than 200 KB

how can I do this

Assume that I want to choose picture with FileUpload from my PC and before uploaded the Image check the size.

string stream = FileUpload1.FileName;
string sub = stream.Substring(stream.LastIndexOf(".") + 1);

FileInfo fileinfo = new FileInfo(Server.MapPath(stream.ToString()));
if (FileUpload1.HasFile)
{
    if (sub == "jpg" || sub == "jpeg" || sub == "png")
    {
        if ((fileinfo.Length / 1024) <= 200)
        {
            string path = Server.MapPath("~/Image/" + stream);
            Image1.ImageUrl = path;
            FileUpload1.SaveAs(path);

            //Image1.DataBind();
            Label1.Text = fileinfo.Length.ToString();
        }
        else
        {
            Label1.Text = "Please insert valid Image";
        }
    }
    else
    {
        Label1.Text = "Please insert valid Image";
    }
}

With this code I'm getting

error is the file not found

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
kamal
  • 19
  • 4

2 Answers2

1

Using FileUpload, you can validate with something like this:

In page:

<asp:FileUpload ID="myFile" runat="server" />

<asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="myFile" ErrorMessage="File size should not be greater than 200 KB." OnServerValidate="CustomValidator1_ServerValidate"></asp:CustomValidator>

In code behind:

protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
    if (myFile.FileBytes.Length > 204800)
    {
        args.IsValid = false;
    }
    else
    {
        args.IsValid = true;       
    }
}

Side note: check the size of 204800, I think is right

Daniele
  • 1,938
  • 16
  • 24
0

Nicer option for user is to check size client side before posting - see JavaScript file upload size validation

With your current code you are getting error because you trying to check file size on disk before actually creating disk file (FileInfo is just information about possible file location and does not mean on exists).

Fix:

  • use FileUpload.FileBytes to check length of the file before trying to save it
  • save file first and than check length if you want to use FileInfo.Length.

If 200K is max upload size on your site you can also restrict max request size in Web.Config, also you'll get very unfriendly error message and may need to do extra work to show something nicer. But it will protect your code from potential abuse by uploading huge files.

Community
  • 1
  • 1
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179