In my asp.net project, I used the custom validator to accomplish this goal. In the validator function, we can check the size, dimension, and type. Make sure to use Page.IsValid in order to show the error messages.
protected void valImage_ServerValidate(object source, ServerValidateEventArgs args)
{
int maxSize = 1024 * 1024;
int maxWidth = 350;
int maxHeight = 225;
if (args.IsValid)
{
if (FileUploadImage.PostedFile.ContentLength > maxSize)
{
args.IsValid = false;
CustomValidatorFile.ErrorMessage = "The image file size must be less than 1 MB.";
}
else if (FileUploadImage.PostedFile.ContentType != "image/jpeg" &&
FileUploadImage.PostedFile.ContentType != "image/pjpeg")
{
args.IsValid = false;
CustomValidatorFile.ErrorMessage = "The image file type must be jpeg.";
}
else
{
GetNewImage(); //put image stream in the session state;
using (Bitmap bitmap = new Bitmap(FileUploadImage.PostedFile.InputStream, false))
{
if (bitmap.Width > maxWidth || bitmap.Height > maxHeight)
{
args.IsValid = false;
CustomValidatorFile.ErrorMessage = "The image dimension must be less than 225px in height and 300px in width.";
}
}
}
}
}
reference: http://aspalliance.com/781_CodeSnip_Validate_Image_Size_Dimension_and_Type_Uploads;
http://www.mikeborozdin.com/post/ASPNET-Image-Uploading-(part-I).aspx
No comments:
Post a Comment