Monday, June 09, 2008

Image size, type Upload Validation

protected void Button1_Click(object sender, EventArgs e)
{
string fileFullname = this.File1.PostedFile.FileName;


if (File1.PostedFile.ContentType.ToUpper().IndexOf("IMAGE") > -1)
{
System.Drawing.Image img = System.Drawing.Image.FromStream(File1.PostedFile.InputStream);
int Width = img.Width;
int Height = img.Height;

if (Width > 200 || Height > 200 || File1.PostedFile.ContentLength > 1024 * 1024 * 200)
{
Response.Write("<script language='javascript'>alert('your image don not confirm the with and height.!');</script>");
}
else
{
if (type == "jpg" || type == "gif" || type == "bmp" || type == "JPG" || type == "GIF")
{

string sPath = Server.MapPath("images/") + dataName + fileName;

string imgPath = "pic/" + dataName + fileName;

this.File1.PostedFile.SaveAs(sPath);

Response.Write("<script language='javascript'>alert('suceed!!!');</script>");


this.Image1.ImageUrl = imgPath;


this.Button1.Enabled = false;
this.Button1.Text = "suceed!";
this.Button1.Enabled = true;

}
else
{
Response.Write("<script language='javascript'>alert('your file type wrong!');</script>");
}
}
}
else
{

Response.Write("<script language='javascript'>alert('please choice the image to upload!');</script>");
}
}

Validations::
We can also use RegularExpressionValidator to validate the file (extensions) which you are uploading. The RE will look like this ^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.jpg|.JPG)$

and now you have to set RequiredFieldValidator for fileUpload. It stops you from proceeding further if you do not upload a file.

No comments: